问题描述
我在 Rails 应用程序中使用了 cancancan gem.但是我对 load_and_authorize_resource
方法的含义不是很清楚.我知道这与调用 load_resource
和 authorize_resource
相同.
I am using the cancancan gem in my rails application. But I am not much clear for the meaning of load_and_authorize_resource
method. I know this is the same as calling load_resource
and authorize_resource
.
load_resource
将创建一个模型的新实例,或者通过 params[:id]
获取一个实例,或者一个实例的集合,然后 authorize_resource
方法将使用这些实例进行授权.但是如果我在每个控制器操作中已经有一个 Model.find(params[:id])
或 Model.new
,我需要添加 load_resource代码>方法?
load_resource
will create a new instance of a model, or get a instance by params[:id]
, or a collection of instances, then authorize_resource
method will use these instances to authorize. But if I already have a Model.find(params[:id])
or Model.new
in each controller action, dose I need to add load_resource
method?
对于某些动作(非RESTful动作),它们与模型没有关系,所以我不需要获取实例,对于这种情况,authorize_resource
如何正常工作?
For some action(Non RESTful actions) , they don't have relationship with model, so I don't need to get a instance, for this situation, authorize_resource
how to work normally?
任何想法都值得赞赏!提前致谢!
Any idea is appreciate! Thanks in advance!
推荐答案
load_and_authorize_resource
为每个动作设置一个 before_filter
以将资源加载到实例变量中并对其进行授权自动地.所以这对 RESTful 操作很有用.现在,如果您在同一控制器中有无法加载资源的非 RESTful 操作,您可以执行以下操作:
The load_and_authorize_resource
sets a before_filter
for each action to load the resource into an instance variable and authorize it automatically. So this is useful for RESTful actions. Now if you have Non RESTful actions in the same controller which can't load the resource you can do:
load_and_authorize_resource only: [:index, :show]
或
skip_load_resource only: :new
这将跳过那些操作的 before_filter
.
This will skip the before_filter
for those actions.
如果你有 Model.find(params[:id])
在控制器中,你可以删除它或只使用:
And if you have Model.find(params[:id])
in controller either you can remove that or just use:
authorize_resource
这些操作不需要 load_resource
.load_resource
也做你手动做的事情.它只是在所有动作中添加一个 before_action
并根据 id
找到对象.
You will not need the load_resource
for these actions. The load_resource
also does the same thing which you have done manually. It just adds a before_action
to all the actions and finds the object according to id
.
并且 load_resource
将始终为您提供与 Model
同名的实例变量,因此如果您在视图中为您的对象使用不同的东西,那么它就赢了也帮不上忙因此,选择一个选项将取决于您和您的代码.
And the load_resource
will always provide you the instance variable with the same name of Model
, so if you are using something different in your views for you object then it won't help too. So choosing an option will depend on you and your code.
Cancancan 维基:
从 CanCan 1.5 开始,您可以使用 skip_load_and_authorize_resource
、skip_load_resource
或 skip_authorize_resource
方法跳过任何应用行为并指定特定操作,例如在前置过滤器中.
希望这会有所帮助.
这篇关于如何理解cancancan gem的load_resource和authorize_resource方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!