skip to content

A turbo-rails broadcast renders a kitchen ticket partial that checks Current.user to show an edit button; why do the boards show the wrong button or fail, and how do you fix it?

level: seniorimportance: should knowfreq 38%

answer

  1. rendered once, sent to everyone
  2. ApplicationController.render, no request
  3. *_later jobs: Current empty in the worker
  4. sync broadcasts leak the actor's view
  5. suppressing_turbo_broadcasts for bulk work

basics

~20 s

Broadcasts render the partial once, outside any request, through ApplicationController.render, and send the same HTML to every subscriber: in a *_later job Current.user is nil, and a synchronous broadcast renders the editor's view for everyone. Keep broadcast partials viewer-independent.

solid answer

~40 s

A turbo-rails broadcast is not a request from the viewer. `broadcasts_to` and the `broadcast_*_later_to` methods render in `Turbo::Streams::ActionBroadcastJob` with `ApplicationController.render`: no session, no cookies, and, in a job worker, empty Current attributes, so `Current.user` is nil and the partial either raises or hides the button. A synchronous `broadcast_replace_to` called during the request renders with the editor's `Current.user` still set, and that one HTML string goes to every board, showing the editor's controls to everyone. Either way there is one render per broadcast, not per viewer. The fix is a partial that depends only on its locals; per-viewer bits move to the client (a Stimulus controller comparing a data attribute with the viewer's id), to a per-user lazy frame, or to separate streams per audience.

code

erb · 7 lines
erb
<%# app/views/tickets/_ticket.html.erb - broken in broadcasts %>
<article id="<%= dom_id ticket %>">
  <%= ticket.dish %>
  <% if Current.user == ticket.user %>
    <%= link_to "Edit", edit_ticket_path(ticket) %>
  <% end %>
</article>

go deeper

for a junior

Recall that a broadcast is rendered once on the server and the same HTML reaches every subscribed page, so it cannot depend on who is viewing.

for a middle

Explain where broadcasts render: ApplicationController.render inside ActionBroadcastJob for *_later calls, the request thread for synchronous ones, and what that does to Current, session and URL helpers.

for a senior

Diagnose the leak or nil error, choose between pure partials, client-side reveal, per-audience streams or refreshes, and control broadcast volume with suppressing_turbo_broadcasts during bulk writes.

for a principal

Set the team rule that broadcast partials take only locals, and weigh one shared render against per-viewer fetches when personalisation grows; each per-audience stream multiplies renders and subscription logic.

## One render, many screens A **broadcast** in turbo-rails is a string of `<turbo-stream>` HTML published to an Action Cable stream name. Every browser subscribed to that name receives the **same bytes**. The server renders the partial **once per broadcast**, not once per viewer, which is what makes broadcasting cheap: a ticket update for a busy kitchen costs one render however many order boards are open. The consequence is that a broadcast partial cannot know who is looking at it. ## Where the rendering happens `Turbo::StreamsChannel`'s broadcast methods render through `ApplicationController.render`, the `ActionController::Renderer` API for rendering outside an action. It builds a mock request env, so: - there is **no session and no cookies**, so helpers that read them see nothing; - `*_url` helpers take their host from the routes' `default_url_options`, not from a real request; - what `Current` holds depends on **which thread** renders. That last point splits into two failure modes: | how the broadcast is sent | where it renders | `Current.user` | symptom | |---|---|---|---| | `broadcasts_to`, `broadcast_*_later_to` | `Turbo::Streams::ActionBroadcastJob` | `nil`: the job runs in a worker, outside any request, so Current attributes start empty | `NoMethodError` on `nil`, or the button never shows | | `broadcast_replace_to` from a callback or controller, in the request thread | the request's thread | the **editor** who saved | every board shows the editor's controls | The second is worse because it works in development with one browser open and leaks in production. ## The fixes 1. **Make broadcast partials pure.** Render only from locals: the ticket, its station, its status. turbo-rails passes the record as a local named after the model (`ticket`), so the partial needs nothing else. 2. **Move per-viewer decisions to the browser.** Render the edit button for everyone, hidden, with `data-owner-id="<%= ticket.user_id %>"`; a Stimulus controller compares it with the viewer's id from a meta tag and reveals it. The server still authorizes the edit action itself, so a revealed button grants nothing. 3. **Split the audience.** Broadcast different partials to different stream names, such as `[kitchen, :chefs]` and `[kitchen, :servers]`, each page subscribing to its own. Renders multiply by the number of audiences, not viewers. 4. **Send less.** Broadcast a refresh or a lazy frame placeholder and let each browser fetch its own HTML through an ordinary request, where `Current.user` is real. That trades one render for one request per viewer. ## Broadcast cost One render per broadcast is cheap, but broadcasts multiply with writes: - `broadcasts_to` sends on **every** commit, including console edits, data migrations and imports; - each `*_later` broadcast is one job, so a 2,000-row import enqueues 2,000 jobs; - wrapping the import in one transaction does not help, because each record's commit callback still fires once the transaction commits. `Ticket.suppressing_turbo_broadcasts { import! }` sets a thread-local flag that the model's broadcast methods check, so everything `broadcasts_to` sends, synchronous or `*_later`, is skipped inside the block. In turbo-rails 2.0.20 two methods ignore the flag: `broadcast_before_to` and `broadcast_after_to`. Afterwards, send one coarse update yourself, such as a replace of the whole `#tickets` list or a refresh. ## Debugging checklist - Does the partial reference `current_user`, `Current`, `session`, `cookies` or `request`? It should not. - Is the broadcast synchronous inside a request? Then it renders as the actor. - Are jobs running at all? Without a worker, `*_later` broadcasts sit in the queue. - Does the partial render the same in `bin/rails console` with `ApplicationController.render(partial: "tickets/ticket", locals: { ticket: Ticket.last })`? If not, it depends on request state. ## Choosing between the fixes - If the difference is cosmetic (a highlight on your own tickets), reveal it on the client. - If the difference is data other viewers must not receive at all, client-side hiding is not enough: the HTML still reaches them. Split the streams, or broadcast a placeholder and let each browser fetch its own version. - If most of the fragment differs per viewer, targeted broadcasts are the wrong tool; an ordinary request per viewer keeps authorization where it already lives, in the controller. ## The model to keep Turbo does not keep per-user state in the browser or filter broadcasts per viewer. The server sends HTML; whatever that HTML says, every subscriber of the stream sees.

  • How do you stop a nightly menu import from sending thousands of Turbo broadcasts?
    Wrap it in `Ticket.suppressing_turbo_broadcasts { ... }`. The class-level, thread-local flag makes the model's broadcast methods, including all three `broadcasts_to` callbacks, return without sending or enqueuing inside the block, and an `ensure` restores the previous value. `broadcast_before_to` and `broadcast_after_to` do not check it. After the import, send one coarse update, for example a replace of the `#tickets` container, instead of one stream per row.
  • Why do *_url helpers in a turbo-rails broadcast partial sometimes produce the wrong host?
    The partial renders through `ApplicationController.render`, which has no real request; when no `http_host` is given, `ActionController::Renderer` derives the host from the routes' `default_url_options`. If those are unset, absolute URLs come out wrong. Use `*_path` helpers in broadcast partials, or set `default_url_options` for the application.

A broadcast is one printed ticket clipped to every station's rail: the printer runs once for the whole kitchen, so the slip cannot say 'your section' differently for each cook reading it.

  • Broadcasts are rendered separately for each subscriber, so current_user works in the partial.
  • A synchronous broadcast is safe to personalise because it renders with the request's user.
  • Passing the user in locals: makes the broadcast reach only that user.
  • Turbo filters broadcast HTML per viewer in the browser, like an SPA store.
  • Wrapping an import in one transaction sends a single broadcast for all rows.