Search code examples
ruby-on-railsauthorizationcancancancancan

How to write CanCanCan Ability for user to read only their data?


How do you restrict user access so a user can only read their own record?

I've tried:

def initialize(user)
  can :read, User, :id => user.id

and this:

def initialize(user)
  can :read, user

but I can still access every user in index and show. I have authorize_resource in the UsersController.

Relevant documentation for reference: https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities


Solution

  • It seems that putting

    authorize! :show, @user
    

    in the show action and

    @users = User.accessible_by(current_ability)
    

    in the index action solves my issue using:

    def initialize(user)
      can :read, User, :id => user.id
    

    I can now see I should have been using load_and_authorize_resource instead of just authorize_resource as it would have automatically added those.