ruby erb javascript 110 lines · 3 tabs

Turbo Streams: optimistic UI for likes with disable-on-submit

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

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

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: optimistic UI for likes with disable-on-submit — share card
Link copied