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
<%= turbo_stream_from [commentable, :comments] %>
<div id="<%= dom_id(commentable, :comments) %>"
data-controller="comments-channel"
data-comments-channel-count-value="<%= comments.size %>">
<% comments.each do |comment| %>
<article id="<%= dom_id(comment) %>" class="comment <%= 'is-deleted' if comment.deleted? %>">
<header>
<strong><%= comment.author.display_name %></strong>
<time datetime="<%= comment.created_at.iso8601 %>">
<%= time_ago_in_words(comment.created_at) %> ago
</time>
</header>
<p><%= comment.deleted? ? "(removed)" : simple_format(comment.body) %></p>
</article>
<% end %>
<%= form_with model: [commentable, Comment.new], data: { turbo_permanent: true }, id: "comment-composer" do |f| %>
<%= f.text_area :body, placeholder: "Add a comment\u2026", rows: 3 %>
<%= f.submit "Post" %>
<% end %>
</div>
class CommentsController < ApplicationController
before_action :set_commentable
def create
@comment = @commentable.comments.build(comment_params.merge(author: current_user))
if @comment.save
respond_to do |format|
format.turbo_stream do
render turbo_stream: turbo_stream.replace(
view_context.dom_id(@commentable, :comments),
partial: "comments/list",
locals: { commentable: @commentable, comments: @commentable.comments.visible },
method: :morph
)
end
format.html { redirect_to @commentable }
end
else
render turbo_stream: turbo_stream.replace("comment-composer", partial: "comments/form",
locals: { commentable: @commentable, comment: @comment }), status: :unprocessable_entity
end
end
def refresh_scroll
render partial: "comments/list",
locals: { commentable: @commentable, comments: @commentable.comments.visible }
end
private
def set_commentable
@commentable = Post.find(params[:post_id])
end
def comment_params
params.require(:comment).permit(:body)
end
end
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static values = { count: Number }
connect() {
this.anchor = null
document.addEventListener("turbo:before-morph-element", this.pin)
document.addEventListener("turbo:morph", this.restore)
}
disconnect() {
document.removeEventListener("turbo:before-morph-element", this.pin)
document.removeEventListener("turbo:morph", this.restore)
}
pin = () => {
this.anchor = window.scrollY
}
restore = () => {
if (this.anchor == null) return
// Keep the reader in place when a broadcast grows the list.
window.scrollTo({ top: this.anchor, behavior: "instant" })
this.anchor = null
}
}
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
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.