问题
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
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?
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!
回答1:
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]
OR
skip_load_resource only: :new
This will skip the before_filter
for those actions.
And if you have Model.find(params[:id])
in controller either you can remove that or just use:
authorize_resource
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
.
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 Wiki:
As of CanCan 1.5 you can use the
skip_load_and_authorize_resource
,skip_load_resource
orskip_authorize_resource
methods to skip any of the applied behaviour and specify specific actions like in a before filter.
Hope this helps.
来源:https://stackoverflow.com/questions/36075500/how-to-understand-load-resource-and-authorize-resource-methods-of-cancancan-gem