[英]Checking action parameters in Rails CanCanCan Authorization
Is it possible to access controller parameters when defining abilities in ability.rb
? 在
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.
但是,我认为阅读较少的动作并能够基于从客户端传递的参数定义功能会容易得多。
@chumakoff has some good info down below that helped explain how CanCanCan is working. @chumakoff下面有一些不错的信息,有助于解释CanCanCan的工作方式。 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. 我决定默认情况下在
ability.rb
授权这些操作,然后引发错误,例如,如果我检测到错误的用户/事件,则在控制器中引发错误raise CanCan::AccessDenied.new("You cannot delete someone else from this event")
。发送的参数ID。
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. 如果我理解正确,则说明您使用的是cancan的
authorize_resource
或load_and_authorize_resource
控制器帮助程序,它们根据控制器操作名称计算用户能力。
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. 只需禁用该动作的默认
cancancan's
行为即可。
Yes there is a debugging tool Named as " pry" . 是的,有一个名为“ 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. 只要您想在代码中检查参数值的地方都使用
binding.pry
,控制台将在此时停止执行,因此您可以检查参数的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.