In a Rails controller, how does a before_action stop the action from running, and why does returning false from it change nothing?
answer
- the terminator checks performed?
- render, redirect_to or head halts
- later callbacks and the action skip
- after_action callbacks skip too
- redirect_to does not return
basics
~20 sA 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.
solid answer
~40 sAction Controller defines its `process_action` chain with a **terminator** that runs each before callback and then asks `performed?` — true once `render`, `redirect_to`, `head` or a send method has produced a response. If it is true, Rails stops: the later `before_action` callbacks do not run, the action does not run, and, because the chain is declared with `skip_after_callbacks_if_terminated: true`, the `after_action` callbacks are skipped as well. The callback's **return value is never inspected**, so `return false` — a habit from model callbacks — halts nothing. Raising an exception also stops the chain, but that is an error path, not a guard. One more trap: `redirect_to` sets the response and returns; code after it in the same method still runs, so write guards as `redirect_to ... unless staff_member?` or return right after.
code
ruby · 15 linesclass BouquetsController < ApplicationController
before_action :set_shop
before_action :require_staff, only: %i[ edit update destroy ]
private
def require_staff
return if staff_member?
redirect_to shop_bouquets_path(@shop), alert: "Staff only."
end
def staff_member?
session[:staff_shop_id] == @shop.id
end
endgo deeper
Know that a before_action stops the action by calling redirect_to, render or head, and that returning false does not stop anything.
Explain the terminator that checks performed?, which callbacks and actions are skipped, why after_action callbacks are skipped too, and the code-after-redirect trap.
Write guards that cannot fall through, test that protected actions had no effect, and move must-run work out of after_action into around_action with ensure.
Decide which checks live in controller guards versus authorization policies or middleware, so access rules stay consistent and auditable across controllers.
## The rule A `before_action` is a guard as well as a loader. In a florist storefront, `require_staff` must keep customers out of `edit`, `update` and `destroy`. Rails does not offer a special "halt" call for this; a before callback halts the chain by **producing a response**. ## How Rails decides to stop `AbstractController::Callbacks` declares the chain like this, in effect: - the callback set is `process_action`; - its **terminator** runs the callback and then returns `controller.performed?`; - `skip_after_callbacks_if_terminated` is `true`. `performed?` is true when the response body has been set or the response committed. In practice that means one of: 1. `render`, including `render :forbidden_page` or `render plain:`; 2. `redirect_to`, for example back to the shop's public page; 3. `head :forbidden` or another status-only response; 4. a send method such as `send_data`. When the terminator returns true, Rails skips the rest of the before callbacks, skips the action, and — because of the second setting — skips every `after_action` callback too. ## What does not halt | Callback does | Halts? | Why | |---|---|---| | `redirect_to new_session_path` | yes | the response body is set | | `head :forbidden` | yes | the response body is set, empty | | `return false` | no | the return value is ignored | | sets `flash[:alert]` only | no | flash is not a response | | raises an exception | stops, as an error | the exception propagates to the rescue handling | Model callbacks in Active Record have their own halting rules; controller callbacks only look at `performed?`, so habits from models do not transfer. ## The "code after redirect_to" trap `redirect_to` is an ordinary method call. It sets the status and the `Location` header and returns; it does not leave the callback. In this guard: ```ruby def require_staff redirect_to shop_path(@shop), alert: "Staff only." unless staff_member? Rails.logger.info("staff access to #{action_name}") end ``` the log line runs for customers too, after the redirect was already chosen. Harmless here, dangerous if the following line renders again or changes data. Write guards so nothing follows the response: a trailing `unless`, an early `return`, or a method that does nothing else. ## What still runs when a before_action halts - **Earlier before callbacks** have already run; their side effects stay. - **Around callbacks** that started before the halting callback finish normally, because their `yield` simply returns. - **The response** that the halting callback produced is sent as is, with whatever status it set; a redirect without an explicit status is a 302. - **`after_action` callbacks** do not run, so anything that must happen on every response belongs in an `around_action` with `ensure`, or in middleware. ## Halting from a parent controller A guard declared in `ApplicationController` halts the chain for every controller below it, before any of their own callbacks run. That is the point of declaring guards high in the hierarchy: a new controller is protected by default. It also explains a classic surprise — a subclass loader such as `set_shop` never runs for a blocked request, so the guard cannot depend on what the subclass would have loaded, unless the loader is moved in front of it. The flip side is that a subclass cannot "un-halt" a parent's guard by declaring its own callbacks; it can only skip the guard by name for some actions. Every such skip is an access-control decision and deserves the same review as the guard itself, because a skip that grows from `only: :index` to the whole controller quietly opens every action. ## Testing guards A request test for a guard checks three things: the status or redirect location, the flash message if any, and that the action's effect did **not** happen — for example, that a bouquet's price is unchanged after a customer's PATCH. The third assertion is the one that catches a guard that sets a flash but forgets to respond. ## Common mistakes - Returning `false` and assuming the chain stopped. - Setting a flash message without redirecting or rendering. - Running code after `redirect_to` in the same callback. - Putting cleanup in `after_action` and expecting it to run for blocked requests.
- Do after_action callbacks run in Rails when a before_action redirects?No. The `process_action` chain is declared with `skip_after_callbacks_if_terminated: true`, so once a before callback halts it by producing a response, the after callbacks are skipped along with the action. Work that must run for every response belongs in an `around_action` with `ensure`.
- Does head :forbidden in a Rails before_action halt the chain even though the body is empty?Yes. `head` sets the response body to an empty string, and `performed?` checks whether a body has been set at all, not whether it has content, so the terminator stops the chain.
- Why can a Rails guard that sets flash[:alert] without redirecting let customers through?Setting the flash does not produce a response, so `performed?` stays false and the chain continues into the action. The flash message then shows on a later page while the protected action has already run.
- Returning false from a before_action halts the chain.
- redirect_to immediately exits the callback method.
- after_action callbacks still run when a before_action redirects.
- Setting flash[:alert] in a before_action stops the action from running.
- A before_action must raise an exception to stop the action.