简体   繁体   中英

Checking action parameters in Rails CanCanCan Authorization

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, eg 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, eg 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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM