ruby erb 64 lines · 4 tabs

Russian Doll Fragment Caching with Touch Propagation in Rails

Shared by codesnips Aug 2026
4 tabs
class Product < ApplicationRecord
  has_many :reviews, dependent: :destroy

  scope :published, -> { where(published: true) }

  def average_rating
    reviews.average(:rating)&.round(2) || 0.0
  end

  # Collection-level key: changes when any review is added, edited, or removed.
  def cache_key_reviews
    count = reviews.count
    max = reviews.maximum(:updated_at)
    "reviews/#{id}-#{count}-#{max.to_i}"
  end
end
4 files · ruby, erb Explain with highlit

Russian doll caching nests fragment caches so that an outer cache is composed of inner caches, and invalidation flows from the innermost changed record outward. The key insight is that Rails builds a cache key from a record's cache_key_with_version, which includes its updated_at timestamp. When a nested record changes, its own fragment is regenerated, and because the parent's key also depends on the child's timestamp, the parent is regenerated too — but only the parts that actually changed are recomputed, while unchanged siblings are served from the cache.

The Product model and Review model set up the association graph. Review declares belongs_to :product, touch: true, which is the load-bearing detail: whenever a review is saved or destroyed, Rails calls touch on the associated product, updating products.updated_at. That timestamp bump is exactly what busts the product's outer fragment. Without touch: true, editing a review would refresh the review's own fragment but leave a stale product wrapper around it. The Product also exposes cache_key_reviews, a helper that combines the review count and the maximum updated_at so a collection-level cache can invalidate when any review changes.

The _product.html.erb partial wraps the whole product in cache product do. Rails derives the fragment name from the product argument automatically. Inside, the reviews collection is rendered with cache: true, which caches each _review fragment individually and fetches them in a single multi-read for efficiency. The nested cache [product, 'stats'] block shows how to add a distinct sub-fragment under the same record with an explicit suffix.

The ProductsController enables caching in the view via render and relies on Rails.cache transparently; no manual invalidation is needed because the keys carry versions. The main trade-off is cache storage growth and reliance on accurate updated_at propagation — deeply nested touch chains can cause write amplification, and belongs_to counter or timestamp updates add overhead on high-write paths. This pattern shines for read-heavy pages with expensive rendering and infrequent, localized edits.


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.

Russian Doll Fragment Caching with Touch Propagation in Rails — share card
Link copied