Russian Doll Caching

suggest change

You may want to nest cached fragments inside other cached fragments. This is called Russian doll caching.

The advantage of Russian doll caching is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.

A cached fragment expires when updated_at changes on the record that fragment depends on. That does not expire a fragment wrapped around it.

For example, the product view:

<% cache product do %>
  <%= render product.games %>
<% end %>

and the game partial. Do not call render game again here. This template is already the game partial, and rendering it again loops.

<% cache game do %>
  <%= game.name %>
<% end %>

If any attribute of game changes, its updated_at moves to the current time and that fragment expires.

However, because updated_at will not be changed for the product object, that cache will not be expired and your app will serve stale data. To fix this, we tie the models together with the touch method:

class Product < ApplicationRecord
  has_many :games
end
class Game < ApplicationRecord
  belongs_to :product, touch: true
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents