In a Rails controller, how does respond_to pick between format.html, format.json and format.csv, and what happens for a format it does not list?
answer
- request.format, then the collector
- .csv suffix sets params[:format]
- browser Accept with */* means HTML
- */* alone picks the first listed
- unlisted: UnknownFormat, 406
basics
~20 srespond_to registers the formats the action serves, then picks the first of request.formats that it lists; a block-less format line renders the matching template, and a format it does not list raises ActionController::UnknownFormat, a 406.
solid answer
~40 sEach `format.html`, `format.json` or `format.csv` line registers a MIME type, with an optional block. Rails then walks `request.formats` in order and takes the first type the block registered. `request.formats` comes from `params[:format]` first (the `.csv` suffix or `?format=csv`), then the Accept header — unless it looks like a browser's, meaning `*/*` sits beside other types — then `js` for XHR, and finally HTML. A client sending only `Accept: */*`, like curl, gets the **first format listed**. A line without a block falls through to the implicit render of that format's template, such as `index.csv.erb`; a block runs instead. If no listed format matches, `respond_to` raises `ActionController::UnknownFormat`, answered with **406 Not Acceptable**.
code
ruby · 11 linesclass VendorsController < ApplicationController
def index
@vendors = Vendor.where(market_day: params[:day]).order(:stall_number)
respond_to do |format|
format.html # index.html.erb
format.json # index.json.jbuilder
format.csv # index.csv.erb
end
end
endgo deeper
Know that respond_to lists the formats an action serves and that a .json or .csv suffix on the URL selects that format.
Explain how request.formats is resolved, why browser Accept headers are ignored, how negotiation picks the first listed match and why unlisted formats get 406.
Order format lines deliberately for wildcard clients, decide which formats deserve explicit blocks, and reject unsupported formats instead of letting them fall through to surprising responses.
Weigh one multi-format action against separate endpoints or an API namespace: shared code and caching on one side, divergent authentication, versioning and error shapes on the other.
## One action, three representations A farmers-market site lists vendors as an HTML page, as JSON for a small map widget, and as a CSV that market staff open in a spreadsheet. In Rails all three come from one `index` action. `respond_to` declares which representations the action supports, and Rails decides which one this request gets. ## Step 1: what format did the request ask for? `request.format` returns the first entry of `request.formats`, which Rails resolves in this order: 1. **`params[:format]`** — set by the optional `(.:format)` segment that resource routes carry, so `/vendors.csv` means CSV, or by a `?format=csv` query parameter. 2. **The Accept header** — but only if it does not look like a browser's. Rails ignores an Accept header in which `*/*` appears together with other types, because browsers send long lists ending in `*/*` that would otherwise produce odd choices. An XHR request's Accept header is honoured even when it contains that wildcard. 3. **Path extension fallback** — a trailing `.xxx` on the path when no format parameter was set. 4. **`Mime[:js]`** for an XHR request, and **`Mime[:html]`** for everything else. `config.action_dispatch.ignore_accept_header = true` skips the Accept step entirely, leaving only the suffix, XHR and HTML rules. ## Step 2: what does the action offer? Inside `respond_to do |format| … end`, each call on the collector — `format.html`, `format.json`, `format.csv` — registers a MIME type, in order. `csv` is one of the types Rails registers out of the box, alongside `html`, `json`, `xml`, `js` and others; new ones are added with `Mime::Type.register`. ## Step 3: negotiation `request.negotiate_mime` walks the request's formats in priority order and returns the first one the collector registered. Two consequences matter in interviews: - **A wildcard picks the first listed format.** `curl` sends `Accept: */*` with nothing else, which is not "browser-like", so the format list is just `*/*` — and `negotiate_mime` returns the first type in the block. Put `format.html` first if that is the safe default. - **No match raises.** If none of the request's formats is registered, `respond_to` raises `ActionController::UnknownFormat`, which Rails maps to **406 Not Acceptable**. ## Step 4: what runs for the chosen format | Line in the block | What happens | |---|---| | `format.html` | Nothing runs now; the implicit render renders `index.html.erb` after the action | | `format.json` | Same, with `index.json.jbuilder` from the jbuilder gem a new full-stack app includes | | `format.csv` | Same, with `index.csv.erb` | | `format.csv { … }` | The block runs and usually renders or sends the data itself | | `format.any` | Matches a requested type that no other line lists | `respond_to` also sets the rendered format, so the implicit render that follows looks for the template of the negotiated format and the response gets that content type. ## Variants ride on formats A `before_action` can set `request.variant = :phone`. Inside `respond_to`, `format.html.phone` or `format.html { |variant| variant.phone }` selects the response for that variant, and `variant.none` covers requests with no variant. The template files that variants render are a view-layer concern. ## Testing the negotiation Each branch deserves a request test, because format resolution happens in the request object rather than in the action code: - `get vendors_path(format: :csv)` exercises the suffix path and should return `text/csv`. - A request with an explicit `Accept: application/json` header and no suffix exercises the Accept path. - A request for an unlisted format, such as `vendors_path(format: :xml)`, should produce 406, which documents the contract. A test for a request without any Accept header documents the HTML default as well. Writing these tests also catches template typos, since a block-less format line depends on the template file existing under the exact expected name. ## Common mistakes - Expecting a browser's Accept header to select JSON; it will not, because of the `*/*` rule — use `/vendors.json` or a request without `*/*`. - Writing the block as `respond_to :html, :json` and also passing a block; Rails raises `ArgumentError`, since it takes types or a block, never both. - Calling `respond_to` twice in one action, which raises `ActionController::RespondToMismatchError` when the second negotiation disagrees with the first. - Forgetting that an unlisted format is a 406, not a silent HTML fallback — which is usually what you want.
- Why does a browser request to a Rails respond_to action get HTML even when JSON is listed first?Browsers send an Accept header such as `text/html,…,*/*;q=0.8`. Because `*/*` appears with other types, Rails treats the header as browser-like and ignores it, so `request.formats` falls back to HTML. Only the format parameter or suffix, an XHR request, or a header without that wildcard pattern changes the format.
- In a Rails controller, how do you serve a phone-specific HTML response with request.variant?Set `request.variant = :phone` in a `before_action`, for example from the user agent. In the action, `format.html.phone` or `format.html { |variant| variant.phone }` selects the phone response, and `variant.none` handles requests without a variant. `request.variant` is an `ArrayInquirer`, so `request.variant.phone?` also works in code.
- Does a Rails action need respond_to to serve both HTML and JSON?No. Without `respond_to`, the implicit render already looks for a template in the requested format, so `index.html.erb` and `index.json.jbuilder` both work. `respond_to` earns its place when formats need different code, or when you want unlisted formats rejected with 406 up front.
- A browser's Accept header decides the format, so Chrome can receive JSON if it is listed first.
- An unlisted format falls back to the HTML template instead of failing.
- A curl request sending Accept: */* always gets HTML, whatever order the formats are listed in.
- Every format line needs a block that calls render, or nothing is sent.
- respond_to :html, :json can be combined with a block to add extra formats.