With turbo-rails, how do turbo_stream_from in a view and broadcasts_to in a model put new kitchen tickets on every open order board?
answer
- a signed name on a custom element
- Turbo::StreamsChannel verifies, then stream_from
- three after_*_commit callbacks
- create and update go through a job
- default target is model_name.plural
basics
~20 sturbo_stream_from @kitchen subscribes the page to a signed stream over Turbo::StreamsChannel; broadcasts_to :kitchen adds commit callbacks that, on create, update and destroy, send append, replace and remove streams rendered from the ticket's partial to that stream.
solid answer
~30 s`turbo_stream_from @kitchen` renders a `<turbo-cable-stream-source>` element carrying `channel="Turbo::StreamsChannel"` and a **signed** stream name derived from the kitchen. On connect it subscribes over the page's shared Action Cable consumer; the channel verifies the signature and calls `stream_from`. In the model, `broadcasts_to :kitchen` registers three callbacks: `after_create_commit` enqueues an append (or `inserts_by: :prepend`) to the target `"tickets"`, `model_name.plural`; `after_update_commit` enqueues a replace of `dom_id(ticket)`; `after_destroy_commit` sends a remove synchronously, because a job could no longer load the deleted row. The create and update broadcasts render `tickets/_ticket.html.erb` in `Turbo::Streams::ActionBroadcastJob`, once, and Action Cable fans the same HTML out to every subscribed board.
code
ruby · 5 linesclass Ticket < ApplicationRecord
belongs_to :kitchen
broadcasts_to :kitchen, inserts_by: :prepend
endgo deeper
Recall the pair: turbo_stream_from in the view subscribes, broadcasts_to in the model sends, and both must name the same streamables.
Explain the three commit callbacks, which action and target each sends, why create and update go through ActionBroadcastJob while destroy does not, and why the partial needs a dom_id root.
Show you can trace a board that did not update: stream name mismatch, missing id on the container or partial, jobs not running, or a rejected subscription. Know when to drop the macro for explicit broadcast calls.
Weigh model-level broadcasting against broadcasting from controllers or jobs: macros are terse but hide side effects in every save, including console edits and imports.
## The two halves A live order board in a restaurant kitchen needs every screen to show a ticket the moment a waiter enters it. turbo-rails splits that into a **subscription** in the view and a **broadcast** from the model, joined by a stream name. ## The subscription: turbo_stream_from `<%= turbo_stream_from @kitchen %>` renders: ```html <turbo-cable-stream-source channel="Turbo::StreamsChannel" signed-stream-name="..."></turbo-cable-stream-source> ``` - The **stream name** is built from the streamables: each one's GlobalID param (`to_gid_param`) or `to_param`, joined with colons, so `turbo_stream_from @kitchen, :tickets` and `[kitchen, :tickets]` on the model side produce the same name. - The name is **signed** with `Turbo.signed_stream_verifier`, so a user cannot edit it to listen to another kitchen. - The custom element subscribes through one shared Action Cable consumer, so ten `turbo_stream_from` tags add ten subscriptions over a single WebSocket, not ten sockets. - `Turbo::StreamsChannel#subscribed` verifies the signed name and calls `stream_from`; an invalid name is rejected. - Blank streamables raise `ArgumentError` ("streamables can't be blank"). ## The broadcast: broadcasts_to `Turbo::Broadcastable` is included into every Active Record model when Active Job is loaded. `broadcasts_to stream, inserts_by: :append, target: broadcast_target_default, **rendering` registers three callbacks: | callback | method called | stream action | target | |---|---|---|---| | `after_create_commit` | `broadcast_action_later_to` | `inserts_by` (default `:append`) | `target`, default `model_name.plural` ("tickets") | | `after_update_commit` | `broadcast_replace_later_to` | `replace` | `dom_id(record)`, such as `ticket_42` | | `after_destroy_commit` | `broadcast_remove_to` | `remove` | `dom_id(record)` | The `stream` argument is either a **symbol**, the name of a method to call on the record (`:kitchen` calls `ticket.kitchen`), or a **lambda** that receives the record (`->(ticket) { [ ticket.kitchen, :tickets ] }`). Extra keywords such as `partial:` pass through to rendering. Its sibling `broadcasts` streams creates to the plural model name and updates and destroys to the record itself. ## What runs where 1. The ticket commits. Because the callbacks are commit callbacks, a rolled-back ticket never reaches a board. 2. For create and update, the `*_later` methods enqueue `Turbo::Streams::ActionBroadcastJob`. The job renders the partial found through `to_partial_path`, here `tickets/_ticket.html.erb`, with the record as the local `ticket`, then calls `ActionCable.server.broadcast`. 3. For destroy, there is no job: the remove stream needs no rendering, and a job could not deserialize a deleted record. The `*_later` jobs `discard_on ActiveJob::DeserializationError` for exactly that case. 4. Action Cable delivers the same payload to every subscriber of the name; each board's Turbo applies the stream to its own DOM. The page must cooperate: - the list container carries `id="tickets"` (the default target), and - the partial's root carries `id="<%= dom_id ticket %>"`, or every later replace and remove finds nothing. ## Customising - `inserts_by: :prepend` puts new tickets on top. - `target: "grill_tickets"` (or a lambda) changes the insertion container. - `partial: "tickets/board_ticket"` swaps the template. - Overriding the class method `broadcast_target_default` changes every default target for that model. - Calling the instance methods yourself (`broadcast_prepend_later_to kitchen, target: "tickets"`) from an explicit callback or a job gives full control when one macro does not fit. ## When a board does not update Work through the chain in order: 1. **Subscription.** The `<turbo-cable-stream-source>` element gains a `connected` attribute once its subscription is confirmed; if it never does, the channel rejected the name or the socket is down. 2. **Stream name.** The view's streamables and the model's must match exactly, in the same order: `turbo_stream_from @kitchen` does not receive `[kitchen, :tickets]`. 3. **Jobs.** Create and update broadcasts wait for a job worker; with no worker running, nothing is sent. 4. **Targets.** The page needs `#tickets` for inserts and `#ticket_42` for replaces; missing ids fail silently. 5. **Rendering.** An exception in the partial fails the job, so check the job's error, not the browser. ## Where the pieces live The WebSocket transport, `ApplicationCable::Connection` and the pub/sub adapter in `config/cable.yml` (Solid Cable in a new Rails 8 app) belong to Action Cable. turbo-rails only adds the channel, the signed names, the helper and the model macros on top.
- With broadcasts_to, why is the destroy broadcast synchronous while create and update use a job?A remove stream needs only the target id, `dom_id(record)`, which is known in the callback, so there is nothing to render. A job, by contrast, receives the record through GlobalID and would fail to load a deleted row; turbo-rails' broadcast jobs `discard_on ActiveJob::DeserializationError`, so a deferred remove would simply vanish. Sending it immediately in `after_destroy_commit` avoids both.
- How would you show a new ticket only on the grill station's board?Name the stream by station: `broadcasts_to ->(ticket) { [ ticket.kitchen, ticket.station ] }` in the model and `turbo_stream_from @kitchen, @station` on that station's board. The stream names match because both sides build them from the same streamables in the same order. Boards subscribed to another station never receive the ticket.
- The cook who created a ticket gets it in the form response and in the broadcast; why is it not shown twice?Before `append` or `prepend`, Turbo removes any existing child of the target whose id matches an element in the incoming template. Both streams carry `id="ticket_42"`, so the second one replaces the first instead of duplicating it, as long as the partial's root carries `dom_id(ticket)`.
- broadcasts_to broadcasts before the transaction commits, so boards may show rolled-back tickets.
- Every broadcasts_to callback renders the partial inside the web request.
- On create, broadcasts_to inserts into the dom_id of the stream object, such as kitchen_1.
- Each turbo_stream_from tag opens its own WebSocket connection.
- The stream name is plain text, so anyone can edit it to watch another kitchen.
- Action Cable renders the partial separately for each subscribed board.