class LikesController < ApplicationController
before_action :set_post
def create
@like = @post.likes.find_or_create_by(user: current_user)
respond_to do |format|
format.turbo_stream do
render turbo_stream: turbo_stream.replace(
dom_id(@post, :like),
partial: "posts/like_button",
locals: { post: @post, liked: true }
)
end
format.html { redirect_to @post }
end
end
def destroy
@post.likes.where(user: current_user).destroy_all
respond_to do |format|
format.turbo_stream do
render turbo_stream: turbo_stream.replace(
dom_id(@post, :like),
partial: "posts/like_button",
locals: { post: @post, liked: false }
)
end
format.html { redirect_to @post }
end
end
private
def set_post
@post = Post.find(params[:post_id])
end
end
<%= turbo_frame_tag dom_id(post, :like) do %>
<div
class="like"
data-controller="like-button"
data-like-button-count-value="<%= post.likes_count %>"
data-like-button-liked-value="<%= liked %>"
>
<% if liked %>
<%= button_to post_like_path(post),
method: :delete,
class: "like__btn like__btn--on",
data: {
action: "turbo:submit-start->like-button#toggle turbo:submit-end->like-button#settle",
turbo_submits_with: "…"
} do %>
♥ <span data-like-button-target="count"><%= post.likes_count %></span>
<% end %>
<% else %>
<%= button_to post_likes_path(post),
method: :post,
class: "like__btn",
data: {
action: "turbo:submit-start->like-button#toggle turbo:submit-end->like-button#settle",
turbo_submits_with: "…"
} do %>
♡ <span data-like-button-target="count"><%= post.likes_count %></span>
<% end %>
<% end %>
</div>
<% end %>
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["count"]
static values = { count: Number, liked: Boolean }
connect() {
this.snapshot = null
}
toggle() {
// Cache current state so a failed request can be rolled back.
this.snapshot = { count: this.countValue, liked: this.likedValue }
const nextLiked = !this.likedValue
const delta = nextLiked ? 1 : -1
this.likedValue = nextLiked
this.countValue = Math.max(0, this.countValue + delta)
this.render()
this.element.classList.add("is-pending")
}
settle(event) {
this.element.classList.remove("is-pending")
if (!event.detail?.success) this.rollback()
// On success the turbo_stream replaces this frame entirely.
}
rollback() {
if (!this.snapshot) return
this.countValue = this.snapshot.count
this.likedValue = this.snapshot.liked
this.render()
}
render() {
if (this.hasCountTarget) this.countTarget.textContent = this.countValue
this.element.classList.toggle("like--on", this.likedValue)
}
}
This snippet shows how a like button gets an instant, optimistic response in the browser while Rails confirms and reconciles the real state over Turbo Streams. The pattern separates two concerns: the immediate feedback the user sees on tap, and the authoritative update the server broadcasts once the write commits. Doing both means the UI feels instantaneous but never drifts from the database.
The LikesController handles the write. It uses find_or_create_by on Like keyed by user_id and post_id, which makes the create idempotent — a double-tap or a retried request can't produce duplicate rows because of the matching unique index. Instead of rendering HTML it responds with turbo_stream, replacing the DOM node whose id comes from dom_id(@post, :like). This turbo_stream.replace targets the same element the button lives in, so the confirmed markup overwrites whatever the optimistic handler drew.
The _like_button partial is the single source of truth for that fragment. Wrapping it in turbo_frame_tag dom_id(@post, :like) (or the equivalent id) means both the controller response and any background broadcast resolve to the same node. The button_to uses data-turbo-submits-with so Turbo automatically disables the button and swaps its label while the request is in flight — this is the built-in guard against duplicate submissions, requiring no custom JavaScript for the disabled state.
The like_button_controller Stimulus handles the optimistic part. On submit it flips the count and pressed state immediately in toggle(), before the server has answered. If the request fails, error() restores the previous DOM from a cached snapshot, so a lost network doesn't leave a phantom like. When the real turbo_stream arrives, it replaces the whole frame and the optimistic guess is discarded either way.
The trade-off is that optimistic UI can briefly show a wrong count under contention; the server broadcast is what makes that self-correcting. This approach fits high-frequency, low-stakes interactions like likes, bookmarks, or reactions — where perceived speed matters more than momentary precision, and where an idempotent write plus an authoritative re-render keeps the two views honest.
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.