How to Use Fragment Caching in Ruby on Rails
In Ruby on Rails, use
cache blocks in your views to enable fragment caching, which stores parts of the page to speed up rendering. Wrap the HTML you want to cache inside cache do ... end in ERB templates, and Rails will save and reuse that fragment automatically.Syntax
The basic syntax for fragment caching in Rails views uses the cache helper method. You wrap the HTML you want to cache inside a cache do ... end block in your ERB template.
You can also provide a cache key or an object to uniquely identify the cached fragment.
erb
<% cache do %> <!-- HTML content to cache --> <% end %> <% cache(@product) do %> <!-- Cached content specific to @product --> <% end %>
Example
This example shows fragment caching in a Rails view that displays a product's details. The cached block stores the product's name and price, so Rails reuses this HTML on subsequent requests without re-rendering it.
erb
<!-- app/views/products/show.html.erb --> <h1>Product Details</h1> <% cache(@product) do %> <p><strong>Name:</strong> <%= @product.name %></p> <p><strong>Price:</strong> $<%= @product.price %></p> <% end %>
Output
<h1>Product Details</h1>
<p><strong>Name:</strong> Coffee Mug</p>
<p><strong>Price:</strong> $12.99</p>
Common Pitfalls
- Not using a unique cache key: If you don't provide a unique key or object, Rails may reuse the wrong cached fragment.
- Stale cache: Cached fragments don't update automatically when data changes; you must expire or update the cache manually.
- Cache misses due to dynamic content: Avoid caching content that changes per user or request unless you use keys that reflect those differences.
erb
<!-- Wrong: no cache key, may cause wrong reuse --> <% cache do %> <p><%= @product.name %></p> <% end %> <!-- Right: use object as cache key --> <% cache(@product) do %> <p><%= @product.name %></p> <% end %>
Quick Reference
- cache do ... end: Wraps the HTML fragment to cache.
- cache(object): Uses the object's cache key for uniqueness.
- expire_fragment(key): Manually expires a cached fragment.
- Rails.cache.clear: Clears all caches (use carefully).
Key Takeaways
Use
cache do ... end blocks in views to enable fragment caching.Provide unique keys or objects to avoid cache collisions and stale content.
Manually expire caches when underlying data changes to keep content fresh.
Avoid caching dynamic user-specific content without proper keys.
Fragment caching improves performance by reusing rendered HTML parts.