ruby erb 45 lines · 4 tabs

Fragment caching inside Turbo Frames (fast lists)

Shared by codesnips Jan 2026
4 tabs
class ProductsController < ApplicationController
  def index
    @products = Product
      .includes(:category)
      .order(created_at: :desc)
      .page(params[:page])
      .per(24)

    respond_to do |format|
      format.html
    end
  end
end
4 files · ruby, erb Explain with highlit

This snippet shows how a paginated product grid is rendered inside a Turbo Frame while leaning on Rails fragment caching to keep re-renders cheap. The pattern combines three ideas: Turbo Frames give lazy, scoped navigation without full page reloads; Russian-doll fragment caching keys each fragment on the record so unchanged rows are pulled straight from the cache store; and touch: true associations invalidate parent caches automatically when children change.

In products_controller.rb, the index action loads a page of products with includes(:category) to avoid N+1 queries and scopes the query with a plain relation. The action does no explicit caching itself — that decision is pushed into the view layer, which is where cache keys can be expressed most naturally against each record. Eager loading matters here because the cached fragment still needs the category name the first time a fragment is written.

In index.html.erb, the whole list lives inside turbo_frame_tag "products". Turbo will intercept pagination links whose data-turbo-frame targets this id, so clicking "Next" swaps only the frame's contents. The outer cache ["products-index", @products] wraps the collection: its key incorporates the max updated_at and count of the relation, so any change to any product busts the outer fragment. Inside it, render partial: "product", collection: uses collection caching (cached: true) so each row is fetched or written individually.

In _product.html.erb, cache product derives a per-record key from the model's cache_key_with_version. Because Product belongs_to :category, touch: true in product.rb, editing a category bumps each product's updated_at, invalidating just those row fragments. The trade-off is write amplification on touch, but reads become nearly free.

This approach shines for large, mostly-static lists that render often but change rarely. Pitfalls to watch: fragments cache rendered HTML, so locale, current-user state, or feature flags must be folded into the cache key or the cache will leak the wrong markup; and collection caching requires the partial name to match the cached key prefix.


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.

Fragment caching inside Turbo Frames (fast lists) — share card
Link copied