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
class Review < ApplicationRecord
belongs_to :product, touch: true
belongs_to :author, class_name: "User"
validates :rating, inclusion: { in: 1..5 }
validates :body, presence: true, length: { maximum: 2_000 }
after_commit :log_touch, on: [:create, :update, :destroy]
private
def log_touch
Rails.logger.debug("Review ##{id} committed; product ##{product_id} touched")
end
end
<% cache product do %>
<article class="product" id="product-<%= product.id %>">
<h2><%= product.name %></h2>
<p class="price"><%= number_to_currency(product.price) %></p>
<% cache [product, "stats"] do %>
<div class="stats">
<span>Rating: <%= product.average_rating %></span>
<span>Reviews: <%= product.reviews.size %></span>
</div>
<% end %>
<section class="reviews">
<%= render partial: "reviews/review",
collection: product.reviews.order(created_at: :desc),
cached: true %>
</section>
</article>
<% end %>
class ProductsController < ApplicationController
def index
@products = Product.published
.includes(:reviews)
.order(updated_at: :desc)
.page(params[:page])
end
def show
@product = Product.includes(reviews: :author).find(params[:id])
fresh_when(@product) # HTTP-level caching on top of fragment caching
end
end
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
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.