0
0
Ruby on Railsframework~7 mins

Russian doll caching in Ruby on Rails

Choose your learning style9 modes available
Introduction

Russian doll caching helps speed up web pages by saving parts of the page separately. When something changes, only the changed parts reload, not the whole page.

You have a page with many parts that update at different times.
You want to avoid reloading the entire page when only a small part changes.
You want to improve your website's speed by caching nested content.
You have a list of items where each item can change independently.
You want to reduce server work by reusing cached pieces inside bigger caches.
Syntax
Ruby on Rails
<%= cache @post do %>
  <h2><%= @post.title %></h2>
  <%= cache @post.comments do %>
    <%= render @post.comments %>
  <% end %>
<% end %>
Use cache helper with an object or key to create a cache block.
Nested cache blocks create the 'Russian doll' effect, caching inner parts separately.
Examples
Caches the whole article block. If the article changes, the cache updates.
Ruby on Rails
<%= cache @article do %>
  <h1><%= @article.title %></h1>
  <p><%= @article.body %></p>
<% end %>
Caches the article and separately caches its comments. Comments cache updates only when comments change.
Ruby on Rails
<%= cache @article do %>
  <h1><%= @article.title %></h1>
  <%= cache @article.comments do %>
    <%= render @article.comments %>
  <% end %>
<% end %>
Caches using a custom key array including timestamp to expire cache when user updates.
Ruby on Rails
<%= cache ['user', user.id, user.updated_at] do %>
  <p><%= user.name %></p>
<% end %>
Sample Program

This example caches the post content and its comments separately. If the post changes, the whole cache updates. If only comments change, only the comments cache updates, saving time.

Ruby on Rails
<!-- app/views/posts/show.html.erb -->
<%= cache @post do %>
  <h2><%= @post.title %></h2>
  <p><%= @post.body %></p>

  <h3>Comments</h3>
  <%= cache @post.comments do %>
    <ul>
      <% @post.comments.each do |comment| %>
        <li><%= comment.body %> - <em><%= comment.author %></em></li>
      <% end %>
    </ul>
  <% end %>
<% end %>
OutputSuccess
Important Notes

Make sure the objects used in cache have a reliable cache_key or use a custom key with timestamps.

Russian doll caching works best when nested parts change independently.

Use Rails development logs or tools like rails dev:cache to check cache hits and misses.

Summary

Russian doll caching caches nested parts of a page separately.

It speeds up pages by only updating changed parts.

Use nested cache blocks with objects or keys to implement it.