In a Rails controller with turbo-rails, when does format.turbo_stream answer a request, and how do you build its response?
answer
- Turbo edits the Accept header
- non-GET form submissions only, unless data-turbo-stream
- text/vnd.turbo-stream.html registered as :turbo_stream
- create.turbo_stream.erb or render turbo_stream:
- applied whatever the status code
basics
~10 sformat.turbo_stream answers when Accept lists text/vnd.turbo-stream.html, which Turbo adds to non-GET form submissions (or GET with data-turbo-stream); you respond with a .turbo_stream.erb template or render turbo_stream: built with the turbo_stream tag builder.
solid answer
~40 sTurbo prepends `text/vnd.turbo-stream.html` to the `Accept` header of every POST, PUT, PATCH or DELETE form submission; links and GET forms get it only with `data-turbo-stream`. turbo-rails registers that media type as `:turbo_stream`, so a `respond_to` block that lists `format.turbo_stream` picks it, and `format.html` still serves everything else. The response is either a template such as `tickets/create.turbo_stream.erb`, where `turbo_stream.prepend "tickets", @ticket` renders the ordinary `_ticket.html.erb` partial, or inline `render turbo_stream: turbo_stream.remove(@ticket)`, which sets the content type for you. Turbo applies a stream response before it looks at the status, so a failed save can answer `status: :unprocessable_content` with a `replace` of the form.
code
ruby · 19 linesclass TicketsController < ApplicationController
def create
@ticket = @kitchen.tickets.build(params.expect(ticket: [ :dish, :table_number ]))
respond_to do |format|
if @ticket.save
format.turbo_stream
format.html { redirect_to kitchen_path(@kitchen), status: :see_other }
else
format.turbo_stream do
render turbo_stream: turbo_stream.replace("new_ticket",
partial: "tickets/form", locals: { ticket: @ticket }),
status: :unprocessable_content
end
format.html { render :new, status: :unprocessable_content }
end
end
end
endgo deeper
Recall that non-GET Turbo form submissions ask for streams, and that you answer with format.turbo_stream plus a create.turbo_stream.erb template or render turbo_stream:.
Explain the Accept header Turbo builds, how respond_to negotiates it, why the tag builder reuses html partials, and why a stream answer can carry a 422.
Show judgement about progressive enhancement: keep the html branch working, decide when a targeted stream beats a redirect, and keep partial ids aligned with dom_id so later streams find their targets.
Consider how far to lean on per-action stream templates versus redirects that refresh the page; every template is a second rendering path a team must keep in step with the page.
## How the request asks for streams Turbo intercepts form submissions and sends them with `fetch`. Its default `Accept` header is `text/html, application/xhtml+xml`. For a submission whose method is **not safe** (POST, PUT, PATCH, DELETE), Turbo prepends the Turbo Streams media type, so the header becomes `text/vnd.turbo-stream.html, text/html, application/xhtml+xml`. - A plain link visit and a `method="get"` form do **not** get the stream type. - Adding `data-turbo-stream` to a link, a form or a submit button opts a GET request in. ## How Rails picks the branch The turbo-rails engine registers the media type: `Mime::Type.register "text/vnd.turbo-stream.html", :turbo_stream`. Inside `respond_to`, Rails walks the request's formats in `Accept` order and takes the first one the block declares. Because Turbo put the stream type first, a block with `format.turbo_stream` answers with streams; a block without it falls through to `format.html` (usually a 303 redirect on success). Keeping `format.html` matters: a client without JavaScript, or a request without the stream type, still works. ## Two ways to write the response 1. **A template.** `app/views/tickets/create.turbo_stream.erb` is found by the usual lookup when `format.turbo_stream` has no block. Inside it, `turbo_stream` is a `Turbo::Streams::TagBuilder`, and each call writes one `<turbo-stream>` element. Several calls in one template send several actions. 2. **Inline.** `render turbo_stream: turbo_stream.remove(@ticket)` uses the `:turbo_stream` renderer turbo-rails adds, which sets the response's content type to `text/vnd.turbo-stream.html` when none was set. The tag builder's arguments: | call | what it writes | |---|---| | `turbo_stream.prepend "tickets", @ticket` | prepend to `#tickets`, rendering `tickets/_ticket.html.erb` | | `turbo_stream.replace @ticket` | replace `#ticket_42` (via `dom_id`) with the ticket partial | | `turbo_stream.update "grill_count", "4"` | update with a literal string | | `turbo_stream.remove @ticket` | remove `#ticket_42`, no template | | `turbo_stream.replace "new_ticket", partial: "tickets/form", locals: {...}` | replace with any partial | Two details trip people up: - The builder adds `:html` to the view's formats and renders records with `formats: :html`, so you **reuse** `_ticket.html.erb`; no `_ticket.turbo_stream.erb` partial is needed. - A record passed as the target becomes `dom_id(record)`, so the partial's root element must carry that id or later `replace` and `remove` streams find nothing. ## Failure responses Turbo checks the response's `Content-Type` before it looks at the status: any response whose media type starts with `text/vnd.turbo-stream.html` is handed to the stream renderer. The Turbo Drive rule (a form submission renders HTML only on a 303 redirect or a 4xx/5xx) is about HTML responses. So a failed save can answer: ```ruby format.turbo_stream do render turbo_stream: turbo_stream.replace("new_ticket", partial: "tickets/form", locals: { ticket: @ticket }), status: :unprocessable_content end ``` In Rails 8.1 on Rack 3.1 or later, `:unprocessable_content` is the name for 422; `:unprocessable_entity` is Rack's obsolete name. ## A complete action On a kitchen order board, a cook adds a ticket from a form at the top of the board: - on success, `create.turbo_stream.erb` prepends the ticket to `#tickets` and replaces the form with a blank one; - on failure, the controller replaces the form with its errors and answers 422; - `format.html` keeps the redirect and the `render :new` path for anything that did not ask for streams. ## Mistakes interviewers listen for - Expecting a plain link click to reach `format.turbo_stream`: it accepts only HTML unless the link carries `data-turbo-stream`. - Writing a separate `_ticket.turbo_stream.erb` partial for every record instead of reusing the html partial through the tag builder. - Choosing the wrong tool: if the page should navigate after the save, redirect; if it should stay and change in place, stream. A stream response never changes the URL. - Forgetting the ids: `turbo_stream.replace @ticket` targets `ticket_42`, so the partial's root must render `id="<%= dom_id ticket %>"`. - Dropping `format.html`, which leaves non-Turbo clients with `ActionController::UnknownFormat`. ## What replaced what Before Turbo, the same effect came from rails-ujs with `remote: true` forms and `format.js` responses that ran JavaScript (`create.js.erb`). That path is retired: the server now sends HTML in stream elements, and behaviour lives in Stimulus controllers.
- With Turbo, how do you get a stream response from a GET request, such as a filter link on the order board?Add `data-turbo-stream` to the link or the GET form (or its submit button). Turbo then prepends `text/vnd.turbo-stream.html` to the request's `Accept` header, so the controller's `format.turbo_stream` branch can answer. Without the attribute a GET visit only accepts HTML, which keeps ordinary navigation and history behaviour intact.
- Why keep a format.html branch next to format.turbo_stream in a Rails controller?Because only Turbo-driven non-GET submissions ask for streams. A request without the stream type in `Accept` (JavaScript off, a native shell visiting a page, a test without `as: :turbo_stream`) falls through to `format.html`; with no html branch it would get `ActionController::UnknownFormat`. The html branch also documents the plain redirect-after-post flow the stream enhances.
- format.turbo_stream answers every Turbo Drive link click.
- A stream response is ignored unless the action redirects with 303.
- Each record needs its own _ticket.turbo_stream.erb partial to be streamed.
- Partial page updates still need format.js and a create.js.erb template.
- render turbo_stream: needs content_type: text/vnd.turbo-stream.html added by hand.
Assumes Rails 8.1 with Turbo 8 via turbo-rails 2.0: the 422 symbol is :unprocessable_content on Rack 3.1+, and params.expect is the Rails 8 strong-parameters form.