skip to content

Filter Chains & Halting

Filters run code around actions: before_action, around_action and skip_before_action, scoped with only: and except:, inherited by subclasses and halted by a render or redirect. A Rails staple.

part ofRuby on Railsread it →
on this pageshow

explore

questions

4

In a Rails controller, what does before_action :set_bouquet, only: %i[show edit update destroy] do, and why do scaffolds generate it?

level: juniorimportance: must knowfreq 82%

answer

  1. runs before the listed actions only
  2. only: becomes an if: on action_name
  3. set_* loader assigns an ivar
  4. find raises RecordNotFound, a 404
  5. raise_on_missing_callback_actions since 7.1

basics

~20 s

It runs the private set_bouquet method before show, edit, update and destroy, so each starts with @bouquet already loaded from the id in the URL; scaffolds generate it so the lookup is written once instead of four times.

solid answer

~40 s

`before_action` adds a callback to the controller's `process_action` chain, which runs around every action. `only:` limits it to the named actions — internally Rails turns `only:` into an `if:` condition on `action_name`, and `except:` into `unless:`. The scaffold's private `set_bouquet` does `@bouquet = Bouquet.find(params.expect(:id))`; because callbacks and the action run on the same controller instance, `@bouquet` is ready in the action and its view. `find` raises `ActiveRecord::RecordNotFound` for a bad id, which Rails answers with 404. Loaders chain naturally: a florist app runs `set_shop` first and then scopes the lookup with `@shop.bouquets.find`, so a bouquet from another shop is a 404 too. In a new Rails 8.1 app, development and test also raise `AbstractController::ActionNotFound` if `only:` names an action that does not exist.

code

ruby · 21 lines
ruby
class BouquetsController < ApplicationController
  before_action :set_shop
  before_action :set_bouquet, only: %i[ show edit update destroy ]
  before_action :require_staff, except: %i[ index show ]

  def show
  end

  private
    def set_shop
      @shop = Shop.find_by!(slug: params.expect(:shop_slug))
    end

    def set_bouquet
      @bouquet = @shop.bouquets.find(params.expect(:id))
    end

    def require_staff
      redirect_to shop_bouquets_path(@shop), alert: "Staff only." unless staff_member?
    end
end

go deeper

for a junior

Read the scaffold's before_action :set_*, only: [...] line, write the private loader, and know that a missing record becomes a 404 through RecordNotFound.

for a middle

Explain only:, except:, if: and unless:, how only: becomes a condition on action_name, why the ivar reaches the action and view, and the raise_on_missing_callback_actions default.

for a senior

Chain loaders so every lookup is scoped through its parent, keep guards and loaders separate and small, and spot callback ordering bugs where a loader depends on one declared later.

for a principal

Decide how much behaviour belongs in callbacks versus explicit calls in actions, balancing duplication against the indirection that makes controllers harder to read.

## What a before_action is An Action Controller **callback** (the guides also call them filters) is a method Rails runs as part of handling an action, outside the action method itself. `before_action :set_bouquet` registers the private method `set_bouquet` to run **before** the action. Callbacks live in one chain per controller, called `process_action`, and that chain wraps every action the controller handles — unless conditions narrow it. ## Scoping with only:, except: and if: - `only: %i[show edit update destroy]` — run for these actions only. - `except: %i[index new create]` — run for every action but these. - `if: :staff_signed_in?` or `unless: -> { request.format.json? }` — run when a method or lambda says so. Rails converts `only:` into an `if:` condition that checks `action_name`, and `except:` into an `unless:` condition. When `only:` and `if:` are combined, every condition must hold. ## The set_* loader pattern The scaffold generator writes this for every resource: 1. `before_action :set_bouquet, only: %i[ show edit update destroy ]` at the top of the class. 2. A private `set_bouquet` that assigns `@bouquet = Bouquet.find(params.expect(:id))`. 3. Actions that use `@bouquet` without loading it, and views that read it. The four member actions all need the same record, so the lookup is written once. The `index`, `new` and `create` actions have no id and are left out. The instance variable works because a fresh controller instance handles each request, and the callback, the action and the template all see that same instance. ## Chaining loaders in a florist storefront A storefront that hosts several flower shops loads the shop first and every bouquet **through** the shop: | Callback | Runs for | Sets or checks | |---|---|---| | `set_shop` | every action | `@shop` from the shop slug in the URL | | `set_bouquet` | show, edit, update, destroy | `@bouquet` from `@shop.bouquets` | | `require_staff` | everything except index and show | staff-only access | Callbacks run in the order they are declared, so `set_shop` must come before `set_bouquet`. Scoping the find through `@shop.bouquets` means a bouquet id from another shop raises `ActiveRecord::RecordNotFound` exactly like a missing one, and Rails turns that into **404 Not Found** without any rescue code. ## Missing actions in only: and except: If `only:` or `except:` names an action the controller does not have — often after a rename — Rails can raise `AbstractController::ActionNotFound` the first time the callback is evaluated. The switch is `config.action_controller.raise_on_missing_callback_actions`; its default became `true` in development and test in Rails 7.1, and a new 8.1 app sets it in both environment files. Production keeps it `false`, so the typo is caught before deploy rather than in front of users. ## How to read a controller's callbacks When a request misbehaves, list the callbacks that apply to the action before reading the action itself: 1. Start with `ApplicationController` and any intermediate base controller; their callbacks run first. 2. Add the controller's own `before_action` lines in order. 3. Drop every callback whose `only:`, `except:`, `if:` or `unless:` excludes the action. 4. Note which callbacks set instance variables and which can respond — a loader that raises 404, a guard that redirects. The result is the real sequence the request goes through, and it usually explains why `@bouquet` is `nil` in one action or why a guard did not fire in another. ## Why not just call the loader inside each action? - **Duplication**: four copies of the same `find` drift apart. - **Ordering**: a callback runs before the action body, so the guard or loader cannot be forgotten halfway down a method. - **Visibility**: the list of callbacks at the top of the class documents what every action depends on. The trade-off is indirection: a reader of `update` must look up to see where `@bouquet` came from. Keep loaders small, name them `set_*`, and keep anything that is not "load" or "guard" inside the action, where it is visible. ## Common mistakes - Making the loader public, which turns it into an action. - Declaring `set_bouquet` above `set_shop` when it depends on `@shop`. - Using `find_by(id: ...)` in a loader and then calling methods on `nil` in the action, instead of letting `find` raise for a 404. - Listing every action in `only:`, which is the same as no `only:` and goes stale when an action is added.

  • What happens in Rails when only: and if: are both given to one before_action?
    Both must hold. Rails turns `only:` into an extra `if:` condition on `action_name` and adds it to any `if:` you passed, so the callback runs only for the listed actions and only when your condition is true.
  • Why does scoping a Rails loader through @shop.bouquets matter for security?
    `@shop.bouquets.find(id)` adds the shop's foreign key to the query, so an id belonging to another shop is not found and raises `ActiveRecord::RecordNotFound`, a 404. `Bouquet.find(id)` would load any shop's bouquet if the user guessed its id.

  • before_action runs after the action unless you pass prepend: true.
  • Instance variables set in a before_action are not visible in the action.
  • only: and except: filter by HTTP verb, not by action name.
  • A loader should use find_by and return nil so the action can decide.
  • A misspelled action in only: is always silently ignored.

Assumes Rails 8.1; the scaffold's params.expect(:id) dates from 8.0, and generated development.rb and test.rb set raise_on_missing_callback_actions = true, a 7.1 default.

open as a page

In a Rails controller, how does a before_action stop the action from running, and why does returning false from it change nothing?

level: middleimportance: must knowfreq 70%

basics

~20 s

A before_action halts the chain by rendering, redirecting or sending head: after each callback Rails checks performed?, and once a response exists the remaining callbacks and the action are skipped. Return values are ignored, so false does nothing.

open as a page

In Rails, in what order do inherited before_action callbacks run, and how do prepend_before_action and skip_before_action change that chain?

level: middleimportance: should knowfreq 50%

basics

~20 s

A subclass inherits its parent's callback chain and appends its own, so ApplicationController's callbacks run first; prepend_before_action inserts at the front, and skip_before_action removes a named callback, or narrows it with only:, raising ArgumentError if it is not in the chain.

open as a page

In a Rails controller, what goes wrong when an around_action forgets to yield or the action raises, and how do after_action callbacks behave in those cases?

level: seniorimportance: should knowfreq 38%

basics

~20 s

An around_action that never yields silently skips the action, later callbacks and after_action callbacks, with no error. If the action raises, after_action callbacks do not run and code after yield is skipped unless it sits in an ensure block.

open as a page