forked from activeadmin/activeadmin
-
Notifications
You must be signed in to change notification settings - Fork 4
How to work with cancan
joseh-henrique edited this page Jul 7, 2012
·
17 revisions
Active_admin works well with CanCan 1.6.7. (1.6.6 was removed)
1.app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= AdminUser.new
case user.role
when "admin"
can :manage, :all
when "editor"
can :manage, Post
cannot [:destroy,:edit], Post
end
end
end
2.app/controllers/application_controller.rb
rescue_from CanCan::AccessDenied do |exception|
redirect_to admin_dashboard_path, :alert => exception.message
end
def current_ability
@current_ability ||= Ability.new(current_admin_user)
end
3.app/admin/admin_users.rb
# encoding: UTF-8
ActiveAdmin.register AdminUser do
menu :if => proc{ can?(:manage, AdminUser) }
controller.authorize_resource
end
Note: If you load_resource
on an index
action, ActiveAdmin will fail.
If you want deep integration between CanCan and ActiveAdmin > 0.4.4, put this gist in a Rails initializer. What it will do for you:
- It will properly load and authorize all your resources.
- Menus will only appear if the current user has the ability to access those resources.
- On the index page, only the actions (links in rightmost column) that the current user has the ability to perform will appear.
- On all resource pages, only the action items (buttons in top-right) that the current user has the ability to perform will appear.
- If you use ActiveAdmin's auto_link helper, it will only create a link if the current user has the ability to view that resource.
The gist has only been tested on the latest ActiveAdmin. It may not work if you are using version 0.4.4.