Complex conditions in CanCanCan can method

1.4k views Asked by At

If I have user,client and request models as follows:

#user.rb


#client.rb
has_one :user
has_many :requests

#request.rb
belongs_to :client

I use user model for CanCanCan authentication. Inside ability class i want to specify ability for client. I want to user to allow read,update only for requests that belong to him. Her is what i try:

def client
  can [:read,:update], [Request], ['client_id = ?', user.client_id] do |client|
      ......something here
  end
end

2

There are 2 answers

0
max On
can [:read, :update], Request, :client_id => user.id
0
Abdul Baig On

here is the simplest option:

can [:read, :update], Request, :client_id => user.id

if you have more complex abilities than this then you can do:

can [:read, :update], Request do |request|
  request.client_id == user.id
end