What does CanCanCan's `load_and_authorize_resource` do in each action of a LoansController, and where does it surprise developers?
answer
- a before_action per controller
- index: accessible_by into @loans
- member actions: find(params[:id]) into @loan
- new and create: build from *_params
- authorize!(params[:action], resource)
basics
~20 sload_and_authorize_resource adds a before_action that loads @loans with accessible_by on index, finds @loan by id on member actions, builds it from strong parameters on new and create, then calls authorize! with the action name on that resource.
solid answer
~40 s`load_and_authorize_resource` in `LoansController` installs a `before_action` that first loads, then authorizes. On `index` it sets `@loans = Loan.accessible_by(current_ability, :index)`; on actions with an `id` it sets `@loan = Loan.find(params[:id])`; on `new` and `create` it builds `Loan.new` from the first of `create_params`, `loan_params` or `resource_params` the controller defines, plus scalar values from the ability's hash conditions. It then calls `authorize!(params[:action].to_sym, @loan || Loan)`. Surprises: a custom action like `renew` is authorized as `:renew`, so it needs its own rule or `:manage`; with no params method, create passes raw params and raises `ActiveModel::ForbiddenAttributesError`; a block-only index rule leaves `@loans` nil; an instance variable you set earlier is not reloaded. `check_authorization` adds an `after_action` raising `CanCan::AuthorizationNotPerformed` when nothing authorized.
code
ruby · 23 linesclass LoansController < ApplicationController
load_and_authorize_resource
def create
# @loan is already built from create_params and authorized for :create
if @loan.save
redirect_to @loan
else
render :new, status: :unprocessable_content
end
end
def renew # authorized as :renew, so the Ability needs a :renew rule
@loan.renew!
redirect_to @loan, status: :see_other
end
private
def create_params
params.expect(loan: [:book_id, :patron_id, :due_on])
end
endgo deeper
Know that load_and_authorize_resource sets @loan or @loans and calls authorize! for the current action.
Explain the per-action table, the params-method lookup order, initial attributes from conditions, and nested loading with through.
Anticipate the traps: custom action names, block rules leaving @loans nil, ForbiddenAttributesError, and after-the-fact check_authorization.
Decide whether convention-driven loading helps the codebase or hides authorization from reviewers reading actions.
## One line, two filters' worth of work `load_and_authorize_resource` is a class macro that adds a single `before_action` to a controller. It combines two halves you can also use separately: - **`load_resource`** sets an instance variable named after the controller (`@loan` or `@loans` in `LoansController`); - **`authorize_resource`** calls `authorize!` with the current action and that resource. Options such as `only:`, `except:`, `class:`, `instance_name:`, `find_by:`, `id_param:`, `through:` and `prepend: true` adjust both halves. ## What happens in each action | Action | Loading | Authorization | |---|---|---| | `index` | `@loans = Loan.accessible_by(current_ability, :index)` | `authorize!(:index, Loan)` | | `show`, `edit`, `update`, `destroy` | `@loan = Loan.find(params[:id])` | `authorize!(:show, @loan)` and so on | | `new`, `create` | `@loan = Loan.new(params)` plus initial attributes | `authorize!(:create, @loan)` for create | | custom member action, e.g. `renew` with an id | `@loan = Loan.find(params[:id])` | `authorize!(:renew, @loan)` | Two details matter for `new` and `create`: 1. **Parameters**: on `create` and `update`, or whenever the model's key is present, CanCanCan looks for a params method in this order: the `param_method:` option, `create_params` (named after the action), `loan_params` (named after the resource), then `resource_params`. With none defined it passes `params[:loan]` unpermitted, and Active Record raises `ActiveModel::ForbiddenAttributesError`. 2. **Initial attributes**: scalar values from the ability's hash conditions are assigned to the new record. With `can :create, Loan, branch_id: user.branch_id`, a librarian's new loan starts at their branch, so the `authorize!(:create, @loan)` check passes. ## Nested resources For `/branches/:branch_id/loans`, declare the parent first: 1. `load_and_authorize_resource :branch` loads `@branch` and authorizes `:show` on it (the parent action defaults to `:show`); 2. `load_and_authorize_resource :loan, through: :branch` loads loans through `@branch.loans`, so a loan from another branch is not found. Without a loaded parent, `through:` raises `CanCan::AccessDenied` unless `shallow: true` lets the child load directly. ## The surprises - **Custom actions need rules.** Authorization uses the literal action name. `can :update, Loan` does not grant `:renew`; add `can :renew, Loan, ...`, an `alias_action :renew, to: :update`, or rely on `:manage`. - **Actions without an id load a collection.** A custom `overdue` action gets `@loans = Loan.accessible_by(current_ability, :overdue)` and is authorized as `:overdue` on the class, so the rules must name it. The `collection:` option is for the rarer collection action that does receive an id. - **Block rules on index.** If the rule for `:index` is block-only, the collection cannot become SQL, so loading is skipped and `@loans` stays `nil`; the class-level `authorize!` still passes. - **Pre-set instance variables win.** If a `before_action` defined earlier already set `@loan` (for example by a slug), CanCanCan does not load it again; this is the documented way to customise loading. - **Update parameters are not assigned.** The loader only finds the record on `update`; the action still calls `@loan.update(loan_params)` itself. ## Reading a controller that uses it Because loading and authorization happen in a filter, the actions themselves look unguarded. Reviewers new to the codebase must know three things before trusting an action: 1. which resource the macro loads (the controller name, unless `class:` or `instance_name:` says otherwise); 2. which action symbol it authorizes, the literal action name; 3. which rule in the Ability grants that action on that resource. A short comment above an unusual action, or an explicit `authorize!` call inside it, saves the next reader from tracing all three. ## Making sure nothing was skipped `check_authorization` in `ApplicationController` adds an `after_action` that raises **`CanCan::AuthorizationNotPerformed`** unless the action called `authorize!` (directly or through `authorize_resource`). `skip_authorization_check` opts a controller or action out, and `check_authorization unless: :devise_controller?` exempts Devise's controllers. Like any after-action check, it reports a forgotten authorization after the action has already run, so it is a development safety net, not a guard. `skip_load_and_authorize_resource`, `skip_load_resource` and `skip_authorize_resource` turn the behaviour off for chosen actions in a subclass.
- Why does load_and_authorize_resource call authorize! with the Loan class on index rather than each record?There is no single record on index. The class check passes when a relevant `can` rule exists, because conditional rules cannot be compared without a record, and the filtering happens in `accessible_by`, which applies the same hash conditions in SQL. Together they mean a user with no index rule is refused, and a user with conditional rules sees only matching rows.
- How do you load a loan by its barcode instead of its id?Pass `find_by: :barcode`. CanCanCan tries `Loan.find_by_barcode!(params[:id])`, then `find_by(barcode: ...)`. Alternatively set `@loan` in an earlier `before_action`; the loader leaves an instance variable that is already set alone and authorizes it.
- load_and_authorize_resource authorizes a custom renew action as :update
- On update it assigns the submitted params to the record
- The index action authorizes each loan individually
- It always reloads the record even if @loan is already set
- check_authorization blocks the action before it runs