Search code examples
ruby-on-railsactiveadmincancan

cancan not working with activeadmin 0.4.4


I am not beeing able to make this work.

I have a project with activeadmin 0.4.4 and devise working, and I need to include role-based permissions to it, so I thought on CanCan. The roles could be 'administrator' or 'publisher', administrator can manage all and publisher only a post section.

I followed https://github.com/gregbell/active_admin/wiki/How-to-work-with-cancan-with-activeadmin, the AdminUser crud it is working fine, and the config.authentication_method = :authenticate_admin_user! was alredy uncomment.

In my ApplicationController I added the following:

  # https://github.com/ryanb/cancan/wiki/exception-handling
    rescue_from CanCan::AccessDenied do |exception|
      respond_to do |format|
        format.html do
          redirect_to admin_root_path, :alert => exception.message
        end
      end
    end

  # https://github.com/ryanb/cancan/wiki/changing-defaults
    def current_ability
      @current_ability ||= Ability.new(current_admin_user)
    end

And here is my Ability class:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= AdminUser.new

    if user.role?('administrator')
      can :manage, :all
    else
      can :read, :all
    end
  end
end

The Ability initialize method is not executing. I tried abort, -as the comments suggest- puts or p, and even sintax error and I have nothing. What am I mising?

I'm stuck here, I also tried http://www.activeadmin.info/docs/13-authorization-adapter.html#using_the_cancan_adapter but it is rising undefined method "authorization adapter", I am not sure if this is working with my activeadmin version. And adding a require active_admin/cancan_adapter rise a LoadError.

Thanks.


Solution

  • Finally I did the trick thanks to http://makandracards.com/jan0sch/13877-rails-activeadmin-and-cancan

    Basically I need to add a controller block in the activeadmin register page for loading it:

    ActiveAdmin.register Whatever do
        #...
        controller do
          load_and_authorize_resource :except => :index
    
          def scoped_collection
            end_of_association_chain.accessible_by(current_ability)
          end
        end
        #...
    end