On a Rails product grid, what does render partial: "products/product", collection: @products, cached: true do differently from a cache block inside each, and what can go wrong?
answer
- one multi-read for the whole grid
- keys built before rendering
- only misses rendered, then write_multi
- lambda key for locale or user
- the query still loads every row
basics
~20 scached: true builds every item's fragment key first, fetches them all with one read_multi, renders only the misses and writes them back with write_multi. A cache block inside an each loop does one store round trip per item.
solid answer
~50 sWith `cached: true`, the collection renderer computes each item's key up front from the partial's path and digest plus the item, so it matches what `cache product` inside the partial would produce, then calls `read_multi` once on the store. Only the misses are rendered, as a smaller collection, and written back with `write_multi`. An `each` loop with a `cache` block makes one read per item, which hurts on a networked store such as Solid Cache or Redis. Pitfalls: the relation still loads every product, because the keys need the records; anything per-user or per-locale inside the partial must go into a key lambda, `cached: ->(product) { [I18n.locale, product] }`; a collection whose items map to different partials raises `NotImplementedError` unless you pass one `partial:`; and `cached: { expires_in: 1.hour }` sets expiry on the written fragments.
code
erb · 6 lines<%# app/views/products/index.html.erb %>
<% cache @products do %>
<%= render partial: "products/product",
collection: @products,
cached: ->(product) { [I18n.locale, product] } %>
<% end %>go deeper
Recall that cached: true on a collection render caches each item's partial and reads them all at once.
Explain the steps: keys built up front, one read_multi, render only misses, write_multi, and why keys match an inner cache block.
Show the production traps: rows still loaded, per-user data frozen into shared fragments, mixed collections raising, key lambdas that explode entry counts.
Decide how list pages layer an outer relation fragment over per-item collection caching, and how much per-user variation the cache can carry.
## Two ways to cache a grid On the outdoor-gear shop's product grid you can cache each card in either of two ways: ```erb <%# 1. A cache block per item %> <% @products.each do |product| %> <% cache product do %> <%= render product %> <% end %> <% end %> <%# 2. Collection caching %> <%= render partial: "products/product", collection: @products, cached: true %> ``` Both produce per-product fragments. The difference is **how many trips** reach the cache store and **how much rendering** happens on a partly warm cache. ## What `cached: true` does The collection renderer (`ActionView::CollectionCaching`) handles the whole collection at once: 1. It computes the digest path of `products/_product` and, for each item, the full fragment key: the `views` prefix, the partial path with its digest, then the item. This is the same key a `cache product do` block **inside** the partial would produce, so the two styles share entries. 2. It calls `read_multi` once with all the keys. 3. It renders only the items whose keys missed, as one smaller collection. 4. It writes the newly rendered fragments with one `write_multi`. 5. It stitches hits and fresh renders back together in the original order. The store it uses is the controller's cache store, which defaults to `Rails.cache`, the store built from `config.cache_store`. Solid Cache, the Redis store and the Memcached store implement multi-key reads natively, so the read is one round trip. The base store falls back to one read per key, which still works but saves nothing. | | Cache block in `each` | `cached: true` | |---|---|---| | Store reads for 48 cards | 48 | 1 | | Rendering on a partly warm cache | each miss rendered as it is met | misses rendered together | | Per-item key customisation | any array in the block | a lambda passed as `cached:` | | Items that map to different partials | fine | raises `NotImplementedError` | ## Customising the key Whatever varies the partial's output must be in the key, or one rendering is served to everyone: ```erb <%= render partial: "products/product", collection: @products, cached: ->(product) { [I18n.locale, current_user.wishlist_version, product] } %> ``` - The lambda receives each item and returns the key source, typically an array. - When a lambda is given and the collection is a relation, Rails preloads the relation's configured associations first, so the lambda can call them without one query per item. - Prefer coarse values in the key, such as a locale or a role, over a user id: a per-user key multiplies the number of entries by the number of users and drives the hit rate towards zero. ## Expiry `cached: { expires_in: 1.hour }` passes the expiry to the `write_multi` that stores the misses. Rails 8.1.3 fixed the renderer so it only forwards `expires_in` when you set it. The caching guide also shows a `key:` entry inside that hash, but the 8.1.4 renderer only calls a lambda passed directly as `cached:` and only reads `expires_in` from a hash, so put a custom key in the lambda form. ## What can go wrong - **The query still runs.** Keys are built from the records, so the controller's relation loads every product. To skip that, wrap the whole grid in an outer fragment keyed on the relation, `cache @products do`, which costs one `COUNT`/`MAX` query instead of loading every row on a hit. - **Mixed collections.** `render @items, cached: true` on a collection whose items map to different partials raises `NotImplementedError` ("render caching requires a template"). Name the partial or split the collection. - **Personal data inside the partial.** A "your rating" badge rendered from `current_user` inside `_product.html.erb` is frozen into whichever user rendered it first. Put the user, or a coarser signal, in the key, or move the badge out of the cached partial. - **Nested freshness.** Collection caching does not change Russian-doll rules: if a card shows reviews, the product must be touched when a review changes. - **Development.** Like the `cache` helper, collection caching only runs when the controller's `perform_caching` is on. ## When to choose which Use `cached: true` for any list rendered through one partial: it saves round trips and batches the rendering of misses. Keep `cache` blocks for single fragments and for nested layers inside the partial. They cooperate, because both produce the same per-item keys.
- Does cached: true skip loading @products from the database?No. The renderer needs every record to build its key, so the relation loads in full. Wrapping the grid in `cache @products do` avoids that on a hit, because a relation's version needs only a `COUNT`/`MAX` query, not the rows.
- Why does render @items, cached: true raise NotImplementedError?When items map to different partials, for example single-table-inheritance subclasses, collection caching has no single template to digest and key against, so the renderer raises "render caching requires a template". Pass `partial:` explicitly or render each subclass group separately.
- cached: true makes Rails skip the SQL query that loads the collection.
- Collection caching uses keys incompatible with cache blocks inside the partial.
- Rails adds current_user to collection cache keys automatically.
- A hash with key: in cached: replaces the default key in Rails 8.1.4.
- cached: true still batches fragment reads when perform_caching is off.