skip to content

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%

answer

  1. around_action must yield
  2. no yield: action silently skipped
  3. after_action needs a successful action
  4. ensure for code after yield
  5. around wraps rendering too

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.

solid answer

~40 s

An `around_action` method receives the rest of the chain as a block and is responsible for running it with `yield` — or `action.call` in the block form. If it never yields, the action, any callbacks declared after it and every `after_action` callback are skipped, and Rails raises nothing; the client gets whatever the callback produced, often an empty response. If the action raises, the exception unwinds through the chain: `after_action` callbacks do not run, and code after `yield` in an around callback is skipped unless it is in an `ensure` block. `after_action` callbacks run only after a successful action, after rendering — they can still change headers on the already-rendered response — and in reverse declaration order. Because the implicit render happens inside the action call, an around callback's timing includes view rendering.

code

ruby · 9 lines
ruby
class OrdersController < ApplicationController
  around_action :only_during_opening_hours, only: :create

  private
    # BUG: outside opening hours nothing yields and nothing renders.
    def only_during_opening_hours
      yield if @shop.open_now?
    end
end

go deeper

for a junior

Remember that an around_action must call yield to run the action, and that after_action only runs when the action succeeded.

for a middle

Explain what yield runs, why skipping it silently drops the action and after callbacks, and why ensure is the place for code that must run after yield.

for a senior

Diagnose empty responses and missing metrics from callback chains, insist that every around branch yields or responds, and move must-run work out of after_action.

for a principal

Decide which cross-cutting concerns belong in controller callbacks versus middleware or instrumentation, weighing per-action precision against failure modes that hide errors.

## What around_action is for An **around callback** wraps the action: code before `yield` runs first, `yield` runs the rest of the chain — later callbacks, the action and its rendering — and code after `yield` runs once that returns. It suits work that must bracket the action, such as timing a florist checkout or tagging log lines with the shop. Two forms exist: - a method that uses `yield`: `around_action :measure_checkout`; - a block that receives the controller and the action: `around_action { |controller, action| ...; action.call }`. ## Failure mode 1: forgetting to yield If the around callback returns without yielding — a conditional that skips `yield`, a rescue that swallows the block — then: 1. the action method never runs; 2. callbacks declared after the around callback never run; 3. `after_action` callbacks never run; 4. **no exception is raised.** Rails' own test suite asserts exactly this: a non-yielding around callback does not raise, and after callbacks are not run. The client receives whatever the callback itself produced — usually nothing, so an empty response. Logs show the request completing quickly with no template rendered, which is the clue. ## Failure mode 2: the action raises When the action, its rendering or a later callback raises, the exception travels back out through the chain: | Callback | Runs when the action raises? | |---|---| | before callbacks | already ran | | code before `yield` in an around callback | already ran | | code after `yield` | **no**, unless it is in `ensure` | | `ensure` in the around callback | yes | | `after_action` callbacks | **no** — they need a successful action | The exception then reaches the controller's rescue handling or the error pages. Anything that must happen on every request — releasing a lock, recording a duration, clearing per-request state — belongs in `ensure` inside an around callback, never in `after_action`. ## What after_action can and cannot do - It runs **after rendering**, because the implicit render happens inside the action call. The body is already built, but the response has not been sent, so headers can still be set: `response.headers["X-Shop"] = @shop.slug`. - It runs only when the action finished without an exception and the chain was not halted by a before callback. - Several after callbacks run in **reverse** declaration order. - It cannot change what was rendered short of replacing the body, which is a sign the logic belongs in the action. ## A safe around callback ```ruby around_action :measure_checkout, only: :create private def measure_checkout started = Process.clock_gettime(Process::CLOCK_MONOTONIC) yield ensure elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started Rails.logger.info("checkout #{action_name} took #{(elapsed * 1000).round} ms") end ``` `yield` is unconditional, and the measurement sits in `ensure`, so it is recorded whether checkout succeeds, renders an error or raises. The duration includes view rendering, because rendering happens inside `yield`. ## Choosing between the three kinds | Need | Use | |---|---| | Load or check something, maybe respond early | `before_action` | | Bracket the action, including failures | `around_action` with `ensure` | | Adjust headers after a successful render | `after_action` | Picking `after_action` for work that must always happen, or `around_action` for a simple guard, is where most callback bugs in production code start. ## Diagnosing in production - **Empty responses from one action family** point at an around callback with a branch that skips `yield`; print the chain with `_process_action_callbacks` and read every around callback that applies. - **Missing headers or metrics on error responses** point at work placed in `after_action`. - **Durations that include view time** are expected from around callbacks; measure inside the action if only the business logic matters. ## Common mistakes - Rescuing exceptions in an around callback without re-raising, which turns errors into silent empty responses. - Wrapping `yield` in a condition, such as a feature flag check, and forgetting the else branch. - Expecting `after_action` to run for failed requests or for requests a guard redirected.

  • Why does a Rails around_action's timing include view rendering?
    The implicit render runs inside the action call, after the action method returns but before control comes back to the around callback. Everything between `yield` going in and coming back — later callbacks, the action and template rendering — is inside the measured span.
  • Where should per-request cleanup go in a Rails controller so it runs even when the action raises?
    In an `ensure` block around `yield` in an `around_action`. `after_action` callbacks run only after a successful action and are skipped both on exceptions and when a before callback halts, while `ensure` runs on every path out of the around callback.

An around_action is a doorman who must open the inner door: if he forgets, the guest never reaches the room, and nobody inside notices anyone was waiting.

  • Rails raises an error when an around_action forgets to yield.
  • after_action callbacks run even when the action raises an exception.
  • after_action runs before the view is rendered, so it can change instance variables.
  • Code after yield in an around_action always runs, even on exceptions.
  • A rescue in an around_action that returns nothing is a safe way to hide errors.