ruby erb 71 lines · 4 tabs

Turbo Streams fallback to HTML for older clients

Shared by codesnips Jan 2026
4 tabs
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

    respond_to do |format|
      if @comment.save
        format.turbo_stream
        format.html { redirect_to @post, notice: "Comment added." }
      else
        format.turbo_stream do
          render turbo_stream: turbo_stream.replace(
            "new_comment",
            partial: "comments/form",
            locals: { post: @post, comment: @comment }
          ), status: :unprocessable_entity
        end
        format.html { render "posts/show", status: :unprocessable_entity }
      end
    end
  end

  private

  def set_post
    @post = Post.find(params[:post_id])
  end

  def comment_params
    params.require(:comment).permit(:body, :author)
  end
end
4 files · ruby, erb Explain with highlit

This snippet shows how a Rails controller can serve a single create action to two very different clients: modern browsers running Turbo, and older or scripting clients (crawlers, integration tests, users with Turbo disabled) that only understand plain HTML redirects. The technique is content negotiation via respond_to, where the response format drives whether the server streams a DOM patch or falls back to a full-page redirect.

In CommentsController, the key is that Turbo registers a custom MIME type, text/vnd.turbo-stream.html, and advertises it in the Accept header on form submissions. The respond_to block branches on format.turbo_stream versus format.html. When the request accepts Turbo Streams, render turbo_stream: sends only the small fragment needed to append the new comment and reset the form. When it does not — the fallback path — the controller issues a classic redirect_to, so the page simply reloads and the comment appears through normal server rendering. The else branch on validation failure mirrors the same split: a turbo_stream.replace for the errored form fragment, or a re-rendered :new with unprocessable_entity for HTML.

Because both paths must produce the same markup, the view logic lives in shared partials rather than being duplicated. create.turbo_stream.erb composes turbo_stream tags that reference comments/comment and comments/form, the exact partials the full HTML page also renders. This is what makes the fallback truly graceful: there is one source of truth for how a comment looks, and Turbo just delivers a surgical slice of it.

The index.html.erb tab ties it together with a turbo_frame_tag and a DOM id (dom_id) that the stream targets. The trade-off worth noting is discipline around ids: the append target and the wrapping element must agree, or the stream silently does nothing. This pattern is worth reaching for whenever an app should feel like an SPA for capable clients while remaining fully functional — and testable, and SEO-friendly — for everyone else, without maintaining two rendering codebases.


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 fallback to HTML for older clients — share card
Link copied