ruby
36 lines · 8 steps
Live-updating comments with Turbo in Rails
A Comment model pushes its own creates, updates, and deletes to subscribers over Turbo Streams.
Explained by
highlit
1class Comment < ApplicationRecord
2 belongs_to :post
3 belongs_to :author, class_name: "User"
4
5 validates :body, presence: true, length: { maximum: 2_000 }
6
7 scope :recent, -> { order(created_at: :desc) }
8
9 after_create_commit :broadcast_creation
10 after_update_commit :broadcast_replacement
11 after_destroy_commit :broadcast_removal
12
13 private
14
15 def broadcast_creation
16 broadcast_prepend_later_to(
17 [post, :comments],
18 target: dom_id(post, :comments),
19 partial: "comments/comment",
20 locals: { comment: self }
21 )
22 broadcast_update_later_to(
23 [post, :comments],
24 target: dom_id(post, :comments_count),
25 html: post.comments.count
26 )
27 end
28
29 def broadcast_replacement
30 broadcast_replace_later_to([post, :comments], target: self)
31 end
32
33 def broadcast_removal
34 broadcast_remove_to([post, :comments], target: self)
35 end
36end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Commit-time callbacks fire only after the transaction succeeds, so broadcasts never reference uncommitted data.
- 2Streaming to a shared `[post, :comments]` stream lets every subscriber receive the same DOM updates.
- 3Targeting elements by `dom_id` keeps server-rendered partials and client DOM in sync without custom JavaScript.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/live-updating-comments-with-turbo-in-rails-explained-ruby-5500/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.