ruby 20 lines · 4 steps

Russian doll caching that busts itself in Rails

How touch: true and composite cache keys keep fragment caches fresh without manual expiry.

Explained by highlit
1module ProductsHelper
2 def cached_product_row(product)
3 cache [product, current_user.role] do
4 render partial: "products/row", locals: { product: product }
5 end
6 end
7end
8 
9class Product < ApplicationRecord
10 belongs_to :category, touch: true
11 has_many :reviews, dependent: :destroy
12 
13 def cache_key_with_reviews
14 "#{cache_key_with_version}/reviews-#{reviews.maximum(:updated_at).to_i}"
15 end
16end
17 
18class Review < ApplicationRecord
19 belongs_to :product, touch: true
20end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Composite cache keys let you vary a fragment by both the record and the viewer without writing expiry code.
  2. 2touch: true propagates updated_at up the association chain so parent caches invalidate when children change.
  3. 3Baking a child's max updated_at into a parent's cache key expires the parent whenever any child is modified.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Russian doll caching that busts itself in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code