Checking action parameters in Rails CanCanCan Authorization

1.5k Views Asked by At

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.

2

There are 2 best solutions below

5
On BEST ANSWER

If I understand correctly, you are using cancan's authorize_resource or load_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:

class ParticipationsController < ApplicationController
  authorize_resource except: :create # skiping `authorize_resource` for `create` action

  # ...

  def create
    if creator_adds_someone_to_event?
      authorize! :add_to, @event
    end

    if user_signs_up_for_event?
      authorize! :sign_up_for, @event
    end
    # ...
  end

So, you can check many different abilities in the same controller action. Just disable default cancancan's behaviour for the action.

0
On

Yes there is a debugging tool Named as " pry" . Use that it would help u out. Just use binding.pry wherever u want to check the value of parameters in the code and the console will stop executing at that moment so u can check the value of the parameters.