ruby erb javascript 113 lines · 4 tabs

Turbo Streams: partial replace with morphing (less jitter)

Shared by codesnips Jan 2026
4 tabs
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
  belongs_to :author, class_name: "User"

  scope :visible, -> { where(deleted_at: nil).order(:created_at) }

  after_create_commit :broadcast_thread
  after_update_commit :broadcast_thread

  def deleted?
    deleted_at.present?
  end

  private

  def broadcast_thread
    broadcast_replace_to(
      [commentable, :comments],
      target: ActionView::RecordIdentifier.dom_id(commentable, :comments),
      partial: "comments/list",
      locals: { commentable: commentable, comments: commentable.comments.visible },
      method: :morph
    )
  end
end
4 files · ruby, erb, javascript Explain with highlit

This snippet shows how Turbo 8 morphing keeps a live-updating comment thread stable instead of blowing away and re-rendering the whole list on every broadcast. The classic replace/update actions swap DOM subtrees wholesale, which resets scroll position, kills focus, and causes visible flicker when a stream arrives while someone is reading or typing. Morphing diffs the incoming markup against the current DOM and mutates only what actually changed, preserving element identity, scroll offset, and input state.

In Comment model, the after_create_commit callback fans out an update through broadcast_replace_to, targeting the stable DOM id dom_id(comment.commentable, :comments). The key detail is method: :morph combined with renderable-style partial rendering: instead of appending a single node, the whole list container is re-rendered and morphed, so add, edit, and soft-delete all flow through one idempotent path. Broadcasting the full container also means the server is the single source of truth for ordering and pagination edges.

In comments/_list.html.erb, the container carries id="<%= dom_id(commentable, :comments) %>" — this id must match the broadcast target exactly, or the morph silently no-ops. The wrapper opts into morphing markers with data-turbo-permanent on the composer so the in-progress textarea is never touched during a diff. Each row is keyed by dom_id(comment); stable ids per element are what let the morph algorithm pair old and new nodes rather than replacing them.

In CommentsController, create responds to turbo_stream by rendering a turbo_stream.replace with method: :morph for the acting user, while the model broadcast handles everyone else subscribed to the channel. refresh_scroll is a small controller action illustrating how a manual refresh reuses the same partial.

In comments_channel.js, a Stimulus-adjacent controller pins the scroll anchor before the stream connects and restores it after, a belt-and-suspenders guard for browsers where native morph scroll preservation lags. The trade-off: morphing costs a full container render and a client-side diff, so very large lists still benefit from pagination or turbo-frame scoping. Reach for this when updates are frequent and the reader's context matters more than raw payload size.


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.

Turbo Streams: partial replace with morphing (less jitter) — share card
Link copied