In a Rails view, how do array keys and cache_if or cache_unless keep per-user markup out of a fragment that every visitor shares?
answer
- the key decides who shares HTML
- cache [product, current_user]
- cache_if condition comes first
- caching? and uncacheable!
- UncacheableFragmentError
basics
~20 sEveryone whose render produces the same key shares the fragment, so per-user markup must enter the key, as in cache [product, current_user.role], or bypass caching: cache_if and cache_unless just render the block when their condition disables caching.
solid answer
~40 sThe `cache` helper keys only on what you pass it, so an edit link for admins cached inside `cache product` is served to every visitor afterwards. Three tools fix that. An **array key**, `cache [product, current_user]`, includes each element's key and version, so each user gets an entry; a coarser element such as a role keeps the hit rate up. **`cache_if condition, product`** caches only when the condition is truthy and otherwise just renders, so `cache_unless current_user&.admin?, product` leaves admins with a live card and caches the anonymous one. And inside helpers, `caching?` tells you whether you are in a cache block, while `uncacheable!` raises `ActionView::Helpers::CacheHelper::UncacheableFragmentError` there, making per-request helpers fail loudly instead of leaking.
code
erb · 8 lines<%# app/views/products/_product.html.erb %>
<% cache_unless current_user&.admin?, [product, I18n.locale] do %>
<h2><%= product.name %></h2>
<p><%= number_to_currency(product.price) %></p>
<% end %>
<%# Personal state stays outside the shared fragment %>
<%= render "products/basket_badge", product: product %>go deeper
Recall that everyone with the same key sees the same cached HTML, so user-specific markup must not sit unguarded inside a cache block.
Explain array keys, cache_if and cache_unless semantics, and how caching? and uncacheable! guard helpers.
Show the cardinality trade-off of per-user keys, choose coarser keys or uncached islands, and catch leaks in review before they ship.
Set the rule for what may enter a shared fragment across the codebase and how per-user state reaches cached pages.
## Who shares a fragment The `cache` helper looks up a fragment by its key: the template path and digest plus whatever you passed. **Everyone whose render computes the same key gets the same HTML.** Nothing about the request, the session or the signed-in user enters the key unless you put it there. That makes the classic leak easy to write: ```erb <% cache product do %> <h2><%= product.name %></h2> <% if current_user&.admin? %> <%= link_to "Edit", edit_product_path(product) %> <% end %> <% end %> ``` Whoever renders the card first decides what everyone sees. If an admin warms the cache, every visitor gets an edit link; if a visitor warms it, admins lose theirs. In an outdoor-gear shop the same goes for "in your basket" badges, member prices or a user's own review highlighted in the list. ## Tool 1: put the variation in the key The helper accepts an array, and each element contributes its own key and version: ```erb <% cache [product, current_user&.role] do %> ``` - A **record** element adds its `cache_key` to the key and its `cache_version` to the version, so `cache [product, current_user]` refreshes when either record changes. - A **plain value** (a role string, `I18n.locale`, a feature-flag name) adds itself to the key. - A `nil` element contributes nothing, so guests share one entry. The trade-off is **cardinality**. Keying by user creates one entry per user per product; most of them are read once and evicted, and the hit rate collapses. Key by the coarsest value that fully determines the markup: a role, a membership tier or a locale. ## Tool 2: skip caching for some renders `cache_if` and `cache_unless` take a condition before the usual key and options: ```erb <% cache_unless current_user&.admin?, product do %> <%= render product %> <% end %> ``` | Helper | Caches when | Otherwise | |---|---|---| | `cache_if(condition, key)` | condition is truthy | yields the block uncached | | `cache_unless(condition, key)` | condition is falsy | yields the block uncached | They suit cases where one small group sees different markup and is cheap to render live: admins, staff previews, a logged-in user in an otherwise public catalogue. The cached entry is then written only by the group that shares it. ## Tool 3: guard helpers that must never be cached Two helpers make the boundary explicit: 1. `caching?` returns true while rendering inside a `cache` block, so a helper can branch. 2. `uncacheable!` raises `ActionView::Helpers::CacheHelper::UncacheableFragmentError` when called inside a cache block. ```ruby module BasketHelper def basket_badge(product) uncacheable! "#{current_basket.quantity_of(product)} in your basket" end end ``` A developer who later moves `basket_badge` inside a cached card gets an exception in development and tests instead of a silent leak in production. ## Keeping personal bits out of the fragment altogether Often the best design keeps the fragment universal and adds personal details another way: - render the personal part **outside** the `cache` block, in a small uncached partial; - send the shared markup cached and fill in user-specific state from the client, for example a Stimulus controller that marks basket items from data the page already has; - for whole sections that differ by audience, cache two variants keyed by audience rather than one per user. ## Checklist for a cached block - List every input to the markup: records, the user, the locale, flags, time. - Each input must be in the key, be excluded from the block, or make the block bypass caching through `cache_if` or `cache_unless`. - Time-dependent output, such as "ends in 3 hours", needs an `expires_in:` or client-side rendering, because no key changes when the clock moves. ## Why tests rarely catch the leak The generated test environment uses `:null_store`, which stores nothing, so every render in a test suite is a miss and one user's fragment is never served to another. A leak therefore shows up first in production, or in development once `bin/rails dev:cache` is on. To reproduce one in a test, give the controller a real store for that test, for example `ActionController::Base.cache_store = :memory_store` with the old value restored afterwards, make sure `perform_caching` is on, render the page as an admin, then as a visitor, and assert the second response has no edit link. Reviewing every new `cache` block against the input checklist above is cheaper and catches more.
- Why is cache [product, current_user] often a poor fix?It is correct but multiplies entries by the number of users, so most fragments are written once and evicted before reuse, and the store fills with near-duplicates. Key by the coarsest value that determines the markup, such as a role or locale, or move the personal part out of the block.
- What does cache_if false, product do with the block?It renders the block normally, without reading or writing the cache, exactly as if no caching helper were there. The condition is evaluated on each render, so the same template can cache for one audience and render live for another.
- Rails adds the signed-in user to fragment keys automatically.
- cache_if with a false condition skips rendering the block.
- Keying every fragment by current_user is the safe default.
- uncacheable! only logs a warning when used inside a cache block.
- The session id is part of every fragment key, so fragments never leak between users.