In a Rails view, what does <% cache product do %> store, under which key, and what makes that fragment stop being served?
answer
- rendered HTML, not records
- views/ prefix plus template path
- digest of the template tree
- cache_version stored beside the key
- perform_caching gates the helper
basics
~20 sThe cache helper stores the HTML its block renders, keyed by the template path, a digest of the template and its partials, and the record's cache_key. A new cache_version (from updated_at) or a template edit makes Rails render it again.
solid answer
~40 s`cache product do ... end` captures the HTML the block renders and writes it to the store behind `Rails.cache`. The key looks like `views/products/index:<digest>/products/42`: the template's path, a digest of that template and the partials it renders, then `product.cache_key`. The record's `cache_version` (its `updated_at` to the microsecond) is stored inside the entry; on read a different version counts as a miss, so saving the product re-renders the block and overwrites the same key. Editing the template changes the digest and therefore the key. On a hit the block never runs. The helper only caches when the controller's `perform_caching` is true; otherwise it just yields, which is why a fresh development app seems to ignore it until `bin/rails dev:cache` is run.
code
erb · 9 lines<%# app/views/products/index.html.erb %>
<% @products.each do |product| %>
<% cache product do %>
<article class="gear-card">
<h2><%= product.name %></h2>
<%= render product.reviews %>
</article>
<% end %>
<% end %>go deeper
Recall that the helper caches the HTML of its block, that a record argument supplies the key, and that saving the record makes the fragment re-render.
Explain the key parts: views prefix, template path with digest, record cache_key, plus the cache_version kept inside the entry and checked on read.
Show you know what does not retire a fragment: other records, helper changes, per-user content. Name how you would make each one visible to the cache.
Weigh where fragment caching pays off against the invalidation work it creates, and how to keep a team's cache keys honest as templates grow.
## What the `cache` helper stores In an ERB template, `cache` wraps a block of markup. The first time the block runs, Action View captures the HTML it produces and writes that string to the application's cache store, the one behind `Rails.cache` and configured by `config.cache_store`. On the next render with the same key and a matching version, the helper reads the string back and inserts it into the page **without executing the block**. Nothing about the record itself is cached: the helper stores **rendered markup**, not Active Record objects and not query results. ```erb <%# app/views/products/index.html.erb in an outdoor-gear shop %> <% @products.each do |product| %> <% cache product do %> <article class="gear-card"> <h2><%= product.name %></h2> <p><%= number_to_currency(product.price) %></p> <%= render product.reviews %> </article> <% end %> <% end %> ``` ## How the key is built A fragment written by `cache product` lives under a key assembled from several parts: | Part | Example | Where it comes from | |---|---|---| | Prefix | `views` | added to every fragment key by `combined_fragment_cache_key` | | Template and digest | `products/index:4f1c...` | the template's virtual path plus a digest of the template and the partials it renders | | Record key | `products/42` | `product.cache_key` | | Version (stored in the entry, not in the key) | `20261006093015123456` | `product.cache_version`, built from `updated_at` | Optional parts slot in as well: `ENV["RAILS_CACHE_ID"]` or `ENV["RAILS_APP_VERSION"]` when either is set, and any controller-wide prefix declared with the `fragment_cache_key` class method. The version is the subtle part. With cache versioning on (the default since `load_defaults 5.2`), the record's timestamp is **not** part of the key string. The store keeps the version inside the entry and, on every read, compares it with the version the current record reports. A mismatch is treated exactly like a miss. ## What retires a fragment 1. **The record changes.** `product.update(price: 189)` moves `updated_at`, so `cache_version` changes; the next render misses, re-runs the block and overwrites the entry under the **same** key. 2. **The template changes.** Editing `index.html.erb`, or a partial the digest knows it renders, changes the digest and so produces a different key; the old entry is never read again and ages out of the store. 3. **The store drops it.** An `expires_in:` passed to the helper (`cache product, expires_in: 12.hours do`), the store's own size or age limits, or a cache clear removes entries. What does **not** retire it on its own: - a change to a *different* record the block displays, such as a review or the product's category; - a change to a helper method the block calls; - a different signed-in user viewing the same card. Those must be expressed through the key, a touch on the parent, or the template digest, which is what Russian-doll caching and template dependencies are about. ## When the helper does nothing The helper checks the controller's `perform_caching` flag first. When it is false, `cache` simply yields and renders the block every time. In a newly generated Rails 8.1 app: - **development** sets `perform_caching` to false unless `tmp/caching-dev.txt` exists, a file `bin/rails dev:cache` toggles; - **test** uses `:null_store`, which keeps nothing, so every render misses; - **production** sets `perform_caching` to true and, after the Solid Cache installer runs, uses `:solid_cache_store`. So "fragment caching does nothing on my machine" is almost always the development toggle, not a broken key. ## Choosing what to wrap - Wrap markup that is **expensive** to render and **shared** by many viewers: product cards, review lists, navigation trees. - Keep per-user details, such as an edit link or a "you bought this" badge, outside the block, or put the user in the key. - Pass a record, a relation or an array of them rather than a bare string. A string key such as `cache "gear-sidebar"` has no version, so only a template edit, an `expires_in:` or eviction ever refreshes it. - Remember that the controller action still runs: `cache` saves view rendering, not the queries the action issued before rendering. Associations loaded lazily inside the block, however, are skipped entirely on a hit. The helper returns `nil` and writes the fragment straight into the template's output buffer, which is why it is written with `<% %>` rather than `<%= %>`.
- What happens if you wrap an unsaved record, as in cache Product.new?An unsaved record's `cache_key` is `products/new` and its `cache_version` is `nil`, so every unsaved product shares one versionless entry. The first rendering is served to everyone afterwards, so a cached block around a new-record form shows stale or foreign content. Keep unsaved records out of fragment keys.
- Does a cache hit skip the queries behind the page?Only the ones the block would have run. The controller action executes before rendering, so `@products = Product.order(:name)` still loads. Associations touched only inside the block, such as `product.reviews`, are skipped on a hit because the block never executes. That is why fragment caching pairs well with lazy loading inside the cached block.
- The cache helper stores the product row so later requests skip the database.
- You must call expire_fragment after every product update.
- Editing the ERB inside the block requires clearing the cache by hand.
- Each product save writes a new key and strands the old entry.
- Fragment caching is active in development as soon as you add the helper.