<div id="image_preview">
<%= render 'images/preview', record: @profile %>
</div>
<% if record.avatar.attached? %>
<%= image_tag record.avatar.variant(resize_to_limit: [240, 240]), class: 'rounded' %>
<% else %>
<div class="text-sm text-gray-500">No image yet</div>
<% end %>
<%= turbo_stream.replace 'image_preview' do %>
<%= render 'images/preview', record: @profile %>
<% end %>
For image uploads, I like immediate previews. With Active Storage, you can render the preview server-side once the blob is attached, and use Turbo Streams to update the preview area. The form submits to an endpoint that attaches the blob and returns a stream replacing #image_preview with a partial that renders an image_tag variant. This keeps image processing logic centralized and avoids client-side FileReader code. It’s also consistent: the preview looks like the final show page. The key is handling validation and returning 422 when the attach fails, updating an error target. If you want truly instant previews before upload, you can add Stimulus, but server-side previews are often enough and much simpler.
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.