Is it possible to access controller parameters when defining abilities in ability.rb
?
I have an event and users that can participate in or create that event. It seems like I could create a different controller action for every possible scenario, e.g. a user signs himself up for an event or a creator deletes someone from the event. However I think it would be a lot easier to read to have less actions and be able to define abilities based on what parameters are being passed in from the client.
Answer
@chumakoff has some good info down below that helped explain how CanCanCan is working. I decided to authorize these actions by default in ability.rb
, and then raise an error, e.g. raise CanCan::AccessDenied.new("You cannot delete someone else from this event")
, in the controller if I detect incorrect user/event parameter IDs being sent in.
If I understand correctly, you are using cancan's
authorize_resource
orload_and_authorize_resource
controller helper that calculates user abilities based on controller actions names.But it's not obligatory to use this helper for all actions. You can skip it for actions having complex ability logic and check abilities manually.
For example:
So, you can check many different abilities in the same controller action. Just disable default
cancancan's
behaviour for the action.