class Comment < ApplicationRecord
belongs_to :post
belongs_to :author, class_name: "User"
validates :body, presence: true
broadcasts_to ->(comment) { [comment.post, :comments] }, inserts_by: :prepend
after_create_commit :broadcast_created
after_update_commit :broadcast_updated
after_destroy_commit :broadcast_removed
private
def broadcast_created
broadcast_prepend_later_to(
[post, :comments],
target: "comments",
partial: "comments/comment",
locals: { comment: self }
)
end
def broadcast_updated
broadcast_replace_to(
[post, :comments],
target: dom_id(self),
partial: "comments/comment",
locals: { comment: self }
)
end
def broadcast_removed
broadcast_remove_to([post, :comments], target: dom_id(self))
end
end
class CommentsController < ApplicationController
before_action :set_post
before_action :set_comment, only: %i[update]
def create
@comment = @post.comments.new(comment_params.merge(author: current_user))
if @comment.save
respond_to do |format|
format.turbo_stream { head :created }
format.html { redirect_to @post }
end
else
render turbo_stream: turbo_stream.replace(
"new_comment", partial: "comments/form", locals: { post: @post, comment: @comment }
), status: :unprocessable_entity
end
end
def update
if @comment.update(comment_params)
head :ok
else
head :unprocessable_entity
end
end
private
def set_post
@post = Post.find(params[:post_id])
end
def set_comment
@comment = @post.comments.find(params[:id])
end
def comment_params
params.require(:comment).permit(:body)
end
end
<%= turbo_stream_from @post, :comments %>
<section class="comments">
<h2>Discussion (<%= @post.comments.size %>)</h2>
<div id="comments">
<%= render partial: "comments/comment", collection: @post.comments.newest_first %>
</div>
<div id="new_comment">
<%= render "comments/form", post: @post, comment: Comment.new %>
</div>
</section>
<%= tag.div id: dom_id(comment), class: "comment", data: { comment_id: comment.id } do %>
<div class="comment__meta">
<strong><%= comment.author.name %></strong>
<time datetime="<%= comment.created_at.iso8601 %>">
<%= time_ago_in_words(comment.created_at) %> ago
</time>
</div>
<div class="comment__body">
<%= simple_format comment.body %>
</div>
<% if comment.author == current_user %>
<%= link_to "Edit", edit_post_comment_path(comment.post, comment), class: "comment__edit" %>
<% end %>
<% end %>
This snippet shows the idiomatic Rails pattern for keeping a live-updating list in sync across every connected browser using Turbo Stream model broadcasts, driven entirely from the model layer. The core idea is that persistence events on an ActiveRecord model become the single source of truth for what the UI should do: a newly created record should be inserted at the top of a list, while an edited record should have its existing DOM node swapped in place. Because Turbo listens on a named stream over Action Cable, no controller code is needed to push these updates — the model announces its own changes.
In Comment model, broadcasts_to wires the record to a stream keyed by its parent post, so every browser subscribed to that post's stream receives updates. The custom callbacks make the create/update distinction explicit: after_create_commit calls broadcast_prepend_to targeting the DOM id comments, which renders the comments/comment partial and inserts it at the top of the list. after_update_commit calls broadcast_replace_to, which finds the element whose id matches dom_id(comment) and replaces just that fragment. Using the *_commit variants matters: broadcasting only after the database transaction commits avoids pushing HTML for a record that could still be rolled back, and prevents readers from fetching a row that isn't visible yet.
Comment model also passes render_later: true implicitly by wrapping heavy broadcasts in broadcast_prepend_later_to in the create path, which offloads partial rendering to a background job so the request returns quickly. The Broadcasts controller demonstrates that the controller stays thin — it only creates the record and responds; the broadcast fan-out happens as a side effect of the commit callbacks.
The view tabs complete the loop. Stream subscription uses turbo_stream_from @post to open the channel, and gives the list container the DOM id comments that the prepend targets. Comment partial wraps each row in dom_id(comment) so the replace action can locate exactly one node. A subtle pitfall is target-id mismatch: the prepend target (comments) and the per-record id from dom_id must line up with the markup, or updates silently vanish. This approach shines for chat, activity feeds, and dashboards where many clients watch the same collection.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<form data-controller="query-sync" data-action="change->query-sync#apply">
<select name="status" class="rounded border p-2">
<option value="">Any</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
Filter UI that syncs query params via Stimulus (no front-end router)
Share this code
Here's the card — post it anywhere.