In a Rails controller, when an action does not render and no template matches the request, when does the client get a 406 and when an empty 204?
answer
- default_render has four branches
- other formats exist: UnknownFormat
- browser GET for HTML: MissingExactTemplate
- anything else: head :no_content
- both exceptions map to :not_acceptable
basics
~20 sIf the action has templates for other formats, Rails raises UnknownFormat (406); if it has none and the request is a non-XHR browser GET for HTML, MissingExactTemplate (406); any other request silently gets 204 No Content.
solid answer
~40 s`ActionController::ImplicitRender#default_render` decides in order. If a template matches the request's format and variant, it renders. If none matches but the action has templates for some other format or variant, it raises `ActionController::UnknownFormat` with the request's formats and variant in the message. If the action has no templates at all and the request is an interactive browser load — a GET, format HTML, not XHR — it raises `ActionController::MissingExactTemplate`. Otherwise it logs `No template found for …, rendering head :no_content` at info level and answers **204 with an empty body**. Both exceptions map to `:not_acceptable` in `rescue_responses`, so the client sees 406. The 204 is the dangerous one: a `fetch` or a PATCH that forgot its template looks successful in a status check while returning nothing.
code
ruby · 12 linesclass VendorsController < ApplicationController
# No toggle_open template of any format exists.
def toggle_open
@vendor = Vendor.find(params.expect(:id))
@vendor.update!(open: [email protected])
end
end
# fetch PATCH with its CSRF token, Accept: application/json
# -> 204 No Content, empty body
# log: No template found for VendorsController#toggle_open,
# rendering head :no_contentgo deeper
Remember that a missing template does not always raise: browser page loads get an error, while some other requests quietly get an empty 204.
Walk through default_render's branches: matching template, UnknownFormat when other formats exist, MissingExactTemplate for a browser GET, and head :no_content otherwise.
Diagnose silent 204s from the info-level log line, the exception messages listing formats and variant, and request.format, then make the action's formats explicit and test bodies, not just statuses.
Decide team conventions that keep implicit behaviour visible: explicit respond_to on multi-format actions, request tests asserting content, and log levels in production that keep the no-content line.
## Where the decision is made When a Rails action returns without calling `render`, `redirect_to`, `head` or a send method, `send_action` calls `default_render`. In a controller that inherits from `ActionController::Base`, that method comes from `ActionController::ImplicitRender`, and it does not simply render or fail: it walks four branches in order. Knowing them turns "the endpoint returns nothing" into a two-minute diagnosis. ## The four branches 1. **A template matches the request.** `template_exists?(action_name, _prefixes, variants: request.variant)` finds, say, `index.json.jbuilder` for a JSON request. It renders. 2. **No match, but the action has templates for other formats or variants.** `any_templates?` is true, so Rails assumes a template was meant to exist and raises `ActionController::UnknownFormat`. The message lists `request.formats` and `request.variant`, which is usually the whole diagnosis. 3. **No templates at all, and the request is an interactive browser load.** The private check `interactive_browser_request?` is `request.get? && request.format == Mime[:html] && !request.xhr?`. Rails raises `ActionController::MissingExactTemplate`, a subclass of `UnknownFormat`; development shows a dedicated "missing exact template" page. 4. **No templates, and not a browser page load.** Rails logs `No template found for VendorsController#toggle_open, rendering head :no_content` at **info** level and sends **204 No Content** with an empty body. ## What the client sees | Request | Templates for the action | Result | |---|---|---| | `GET /vendors.csv` | only `index.html.erb` and `index.json.jbuilder` | `UnknownFormat`, 406 | | Browser `GET /vendors/7/stats` | none | `MissingExactTemplate`, 406 | | `fetch` PATCH with `Accept: application/json` | none | 204, empty body | | Browser `GET /vendors` | `index.html.erb` | the template, 200 | Both exceptions are mapped to `:not_acceptable` in `ActionDispatch::ExceptionWrapper.rescue_responses`, which is what turns them into a 406; how error pages are then rendered is the error-handling layer's job. ## Why the 204 branch bites in production - The status is a success code, so a request test that only checks `assert_response :success` passes. - Front-end code that calls `response.json()` on the empty body fails far from the cause. - The only server-side trace is an **info** log line, easy to miss when production logs are filtered. - Typical triggers: a member action added for a `fetch` call without a matching `.json.jbuilder` file, a template whose name does not match the action, such as `toggle-open.json.jbuilder` for `toggle_open`, or a template saved under the wrong controller folder. ## Diagnosing and fixing - Read the log for the `rendering head :no_content` line, or the exception message, which prints the formats and the variant Rails looked for. - Check what `request.format` resolved to: a `.json` suffix, the Accept header or an XHR flag can each change it. - Decide what the action should answer and say so explicitly: add the missing template, list the formats it serves in a `respond_to` block so unlisted ones fail fast with 406, or respond with an explicit status. - Assert on the body or the content type in request tests, not only on a 2xx status. ## Catching it in tests Request tests are the cheapest guard, because they exercise the real format resolution and the real template lookup. - Assert on the **content type** as well as the status: a JSON endpoint should answer `application/json`, and a 204 has none. - Assert on something **in the body**, such as a vendor name in the parsed JSON, so an empty response fails loudly. - Add one test per format the action promises, including the suffix form such as `/vendors.csv`, because each format takes its own path through `default_render`. - For actions that are meant to answer 204, say so explicitly in the action, so the intent is visible in code rather than inferred from a missing file. - Keep production log levels at info or below for at least the controller log lines, so the `rendering head :no_content` message survives when someone needs it. ## Why Rails chose these rules A browser page load that renders nothing is almost certainly a bug, so Rails fails loudly. A request for a format the action clearly supports elsewhere is also a likely mistake, so it fails loudly too. A non-browser request to an action with no templates at all is treated as an action whose job is a side effect, and 204 is the honest HTTP answer for "done, nothing to show". The rules are reasonable defaults; the trap is assuming the third and fourth branches behave the same.
- Why does a Rails XHR GET for HTML to an action without templates get 204 instead of MissingExactTemplate?MissingExactTemplate is reserved for interactive browser loads: a GET, format HTML, and not XHR. An XHR request fails the last test, so `default_render` falls through to the final branch and answers `head :no_content`. The same applies to any non-GET request.
- In a Rails controller, how would you make an action fail fast for formats it does not serve instead of returning 204?Declare the formats in a `respond_to` block. An unlisted format makes `respond_to` raise `ActionController::UnknownFormat`, which becomes 406, before the implicit render's fallback is ever reached. Alternatively, respond explicitly for every case so no request depends on the fallback.
- Every missing template raises an exception, so a broken endpoint always shows up as an error.
- A 204 from an action means the developer called head :no_content somewhere.
- MissingExactTemplate is raised for any request format, including JSON from fetch.
- UnknownFormat and MissingExactTemplate become 500 Internal Server Error responses.
- assert_response :success proves a JSON action rendered its template.