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.
As explained in the previous section, a cached file will expire if the value of updated_at
changes for a record on which the cached file directly depends. However, this will not expire any cache the fragment is nested within.
For example, take the following view:
<% cache product do %>
<%= render product.games %>
<% end %>
Which in turn renders this view:
<% cache game do %>
<%= render game %>
<% end %>
If any attribute of game is changed, the updated_at
value will be set to the current time, thereby expiring the cache.
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