Search code examples
ruby-on-railscancan

How to get User from CanCan Ability


In CanCan, an ability is assigned to an individual user. Is there a way to access that user when you have an ability record.

I'd like to be able to say:

@ability = Ability.new(User.find(3))
@ability.based_on_user # Does not exist, but would respond with the same thing as User.find(3)

In my app, users can impersonate other users, which involves resetting @current_ability = Ability.new(@impersonated_user) and I'd like to be able to quickly get that user for debugging purposes. The documentation doesn't give any such method, but I would be okay with a hack, since it's just for my own purposes in testing.


Solution

  • Just add that method yourself to your ability model. Something like this:

    # in app/models/ability.rb
    class Ability
      include CanCan::Ability
    
       def initialize(user)
         @user = user
    
         # the rest of your code
       end
    
       def based_on_user
         @user
       end
    end