Reputation: 6787
I need to add a filter on users. A user can see other users only if the user belongs to same branch. One user can belong to multiple branches.
I am defining ability with the blocks below. But after referring to documentation and facing an error I got to know that the index
method doesn't fit well with defining the ability with block.
#This code is part of initialisation method of ability.rb
can :index, User do |curr_user|
#check if user belongs to same branch
!curr_user.branch_ids.index(branch_id).nil?
end
Here is index method of users controller
def index
authorize! :index, User
@users = User.where(params[:user]).accessible_by(current_ability, :index)
renders :obj =>@users
end
What is some alternative to define abilities to implement this logic in place of defining abilities with blocks?
Upvotes: 1
Views: 1574
Reputation: 66
accessible_by
is like a where
for AR...
You should use a hash of conditions rather than a block to define your ability see Defining-Abilities
Something like ...
def initialize(user)
conditions = branch_id: user.branch_id
can :read, User, conditions
end
I suggest you first spike correct conditions
in irb console
user = User.first
User.where(branch_id: user.branch_id)
Then you might want a test
Upvotes: 1