Skip to content

How to work with cancan

rtlong edited this page Mar 29, 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: It is very important that you do not use the normal cancan load_and_authorize_resource, as this will cause ActiveAdmin to fail

If you intend to use CanCan on every resource, you can use this (at the end of your initializer) instead of specifying it on every registration:

ActiveAdmin::ResourceController.class_eval do
  authorize_resource
end
Clone this wiki locally