Concept Flow - Fragment caching
Render View
Check Cache for Fragment
Use Cached
Insert Cached
Continue Rendering
Send Response
Rails checks if a cached fragment exists. If yes, it uses it. If no, it renders and caches the fragment before continuing.
<% cache('menu') do %>
<ul>
<li>Home</li>
<li>About</li>
</ul>
<% end %>| Step | Action | Cache Check Result | Fragment Rendered | Cache Updated | Output |
|---|---|---|---|---|---|
| 1 | Start rendering view | N/A | No | No | No output yet |
| 2 | Check cache for key 'menu' | Miss (not found) | No | No | No output yet |
| 3 | Render fragment inside cache block | N/A | Yes | No | <ul><li>Home</li><li>About</li></ul> |
| 4 | Store rendered fragment in cache with key 'menu' | N/A | Yes | Yes | <ul><li>Home</li><li>About</li></ul> |
| 5 | Continue rendering rest of view | N/A | Yes | Yes | <ul><li>Home</li><li>About</li></ul> + rest of view |
| 6 | Next request: Check cache for key 'menu' | Hit (found) | No | No | <ul><li>Home</li><li>About</li></ul> from cache |
| 7 | Insert cached fragment, skip rendering | Hit (found) | No | No | <ul><li>Home</li><li>About</li></ul> from cache |
| 8 | Continue rendering rest of view | N/A | No | No | <ul><li>Home</li><li>About</li></ul> from cache + rest of view |
| Variable | Start | After Step 2 | After Step 4 | After Step 6 | Final |
|---|---|---|---|---|---|
| cache['menu'] | nil | nil | <ul><li>Home</li><li>About</li></ul> | <ul><li>Home</li><li>About</li></ul> | <ul><li>Home</li><li>About</li></ul> |
Fragment caching in Rails: Use <% cache(key) do %> ... <% end %> to cache parts of views. Rails checks cache for the key before rendering. If found, cached HTML is used directly. If not, fragment renders and stores in cache. Speeds up repeated view rendering by reusing HTML.