0
votes

I am having some issues with cancan and I dont know what I am doing wrong.

in my /rails_admin.rb

config.authorize_with :cancan

in my models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
      user ||= User.new # guest user (not logged in)
      if user.admin?
        can :manage, :all
      else
        can :read, :all
      end
end

I do have a admin? method that gives a true or false value and tested it and it works.

The problem is that my Ability class is not initializing with a user. If I were to put binding.pry under the def initialize(user) i get nil win I call user. What am I missing?

1

1 Answers

0
votes

Where you are calling authorize! does the 'current_user' field / method exist or is it nil there as well?

CanCan expects that you have the 'current_user' method defined.

Many of the popular gems used for authentication, such as Devise, will give you this automatically.

If you have written your own login scripts, you will need to provide a helper or controller method called 'current_user' that returns the user currently logged in.

Edit: Reference to some more details about what CanCan expects

GitHub: cancan: Changing Defaults