Method: CanCan::ControllerAdditions::ClassMethods#authorize_resource

Defined in:
lib/cancan/controller_additions.rb

#authorize_resource(*args) ⇒ Object

Sets up a before filter which authorizes the resource using the instance variable. For example, if you have an ArticlesController it will check the @article instance variable and ensure the user can perform the current action on it. Under the hood it is doing something like the following.

authorize!(params[:action].to_sym, @article || Article)

Call this method directly on the controller class.

class BooksController < ApplicationController
  authorize_resource
end

If you pass in the name of a resource which does not match the controller it will assume it is a parent resource.

class BooksController < ApplicationController
  authorize_resource :author
  authorize_resource :book
end

Here it will authorize :show, @author on every action before authorizing the book.

That first argument is optional and will default to the singular name of the controller. A hash of options (see below) can also be passed to this method to further customize it.

See load_and_authorize_resource to automatically load the resource too.

Options:

:only

Only applies before filter to given actions.

:except

Does not apply before filter to given actions.

:singleton

Pass true if this is a singleton resource through a has_one association.

:parent

True or false depending on if the resource is considered a parent resource. This defaults to true if a resource name is given which does not match the controller.

:class

The class to use for the model (string or constant). This passed in when the instance variable is not set. Pass false if there is no associated class for this resource and it will use a symbol of the resource name.

:instance_name

The name of the instance variable for this resource.

:through

Authorize conditions on this parent resource when instance isn’t available.

:prepend

Passing true will use prepend_before_action instead of a normal before_action.



180
181
182
# File 'lib/cancan/controller_additions.rb', line 180

def authorize_resource(*args)
  cancan_resource_class.add_before_action(self, :authorize_resource, *args)
end