0
0
RailsHow-ToBeginner · 4 min read

Russian Doll Caching in Ruby on Rails: How to Use It Effectively

Use cache blocks nested inside each other in your Rails views to implement Russian Doll Caching. This technique caches parent and child fragments separately, so when a child changes, only its cache updates without invalidating the parent cache.
📐

Syntax

Russian Doll Caching uses nested cache blocks in Rails views. Each block caches a fragment of the view, often keyed by model objects or versions.

  • cache @post do: caches the post fragment.
  • cache comment do: caches each comment inside the post.
  • Nested caches allow partial updates without clearing the whole parent cache.
erb
<% cache @post do %>
  <h2><%= @post.title %></h2>
  <div>
    <% @post.comments.each do |comment| %>
      <% cache comment do %>
        <p><%= comment.body %></p>
      <% end %>
    <% end %>
  </div>
<% end %>
💻

Example

This example shows caching a blog post and its comments separately. When a comment changes, only its cache updates, keeping the post cache intact.

erb
<!-- app/views/posts/show.html.erb -->
<% cache @post do %>
  <h1><%= @post.title %></h1>
  <p><%= @post.body %></p>
  <h3>Comments:</h3>
  <ul>
    <% @post.comments.each do |comment| %>
      <% cache comment do %>
        <li><%= comment.body %> - <em><%= comment.user.name %></em></li>
      <% end %>
    <% end %>
  </ul>
<% end %>
⚠️

Common Pitfalls

1. Not using unique cache keys: Always use model objects or versions to generate keys, or caches may not expire correctly.

2. Forgetting to expire child caches: If child objects change but their cache keys don’t, the cache won’t update.

3. Over-nesting caches: Too many nested caches can complicate cache management and reduce performance benefits.

erb
<!-- Wrong: Using static keys causes stale cache -->
<% cache 'post' do %>
  <h1><%= @post.title %></h1>
<% end %>

<!-- Right: Use model object for dynamic keys -->
<% cache @post do %>
  <h1><%= @post.title %></h1>
<% end %>
📊

Quick Reference

  • Use cache model_object to create unique cache keys automatically.
  • Nest cache blocks to cache parent and child fragments separately.
  • Expire caches by updating model timestamps or using touch on associations.
  • Check cache hits/misses in Rails logs to verify caching behavior.

Key Takeaways

Russian Doll Caching nests cache blocks to cache parent and child view fragments separately.
Use model objects or versions as cache keys to ensure proper cache expiration.
Update child caches independently without invalidating the parent cache.
Avoid static cache keys to prevent stale content.
Monitor Rails logs to confirm caching works as expected.