ruby erb 106 lines · 4 tabs

Model broadcasts: prepend on create, replace on update

Shared by codesnips Jan 2026
4 tabs
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
4 files · ruby, erb Explain with highlit

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

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
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

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
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

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<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)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Model broadcasts: prepend on create, replace on update — share card
Link copied