Bird
Raised Fist0
Ruby on Railsframework~10 mins

Fragment caching in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
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.
Execution Sample
Ruby on Rails
<% cache('menu') do %>
  <ul>
    <li>Home</li>
    <li>About</li>
  </ul>
<% end %>
This code caches the HTML list inside the cache block under the key 'menu'.
Execution Table
StepActionCache Check ResultFragment RenderedCache UpdatedOutput
1Start rendering viewN/ANoNoNo output yet
2Check cache for key 'menu'Miss (not found)NoNoNo output yet
3Render fragment inside cache blockN/AYesNo<ul><li>Home</li><li>About</li></ul>
4Store rendered fragment in cache with key 'menu'N/AYesYes<ul><li>Home</li><li>About</li></ul>
5Continue rendering rest of viewN/AYesYes<ul><li>Home</li><li>About</li></ul> + rest of view
6Next request: Check cache for key 'menu'Hit (found)NoNo<ul><li>Home</li><li>About</li></ul> from cache
7Insert cached fragment, skip renderingHit (found)NoNo<ul><li>Home</li><li>About</li></ul> from cache
8Continue rendering rest of viewN/ANoNo<ul><li>Home</li><li>About</li></ul> from cache + rest of view
💡 Execution stops after full view is rendered and response sent.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6Final
cache['menu']nilnil<ul><li>Home</li><li>About</li></ul><ul><li>Home</li><li>About</li></ul><ul><li>Home</li><li>About</li></ul>
Key Moments - 2 Insights
Why does Rails skip rendering the fragment on the second request?
Because the cache check at step 6 finds the fragment stored at step 4, so it uses the cached HTML instead of rendering again.
What happens if the cache key changes?
Rails treats it as a cache miss, so it renders the fragment again and stores it under the new key, as shown by the cache miss at step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the cache check result at step 6?
AHit (found)
BMiss (not found)
CError
DNot checked
💡 Hint
Check the 'Cache Check Result' column at step 6 in the execution_table.
At which step is the fragment first stored in the cache?
AStep 6
BStep 2
CStep 4
DStep 8
💡 Hint
Look at the 'Cache Updated' column to find when the cache is updated.
If the cache key changes, what will happen at the cache check?
ACache hit and fragment reused
BCache miss and fragment rendered again
CCache cleared automatically
DError thrown
💡 Hint
Refer to the key_moments explanation about cache key changes causing misses.
Concept Snapshot
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.
Full Transcript
Fragment caching in Rails helps speed up rendering by saving parts of the view as HTML in cache. When Rails renders a view with a cache block, it first checks if the cached fragment exists for the given key. If it does, Rails inserts the cached HTML directly, skipping rendering. If not, Rails renders the fragment, stores it in cache, then continues rendering the rest of the view. On subsequent requests, the cached fragment is reused until the cache expires or is cleared. This reduces repeated work and improves performance.

Practice

(1/5)
1. What is the main purpose of fragment caching in Rails?
easy
A. To manage database connections efficiently
B. To store user login information securely
C. To save parts of a page so they load faster next time
D. To compress images for faster download

Solution

  1. Step 1: Understand fragment caching concept

    Fragment caching stores parts of a webpage to avoid regenerating them every time.
  2. Step 2: Identify the main benefit

    This speeds up page rendering by reusing cached parts instead of rebuilding them.
  3. Final Answer:

    To save parts of a page so they load faster next time -> Option C
  4. Quick Check:

    Fragment caching = save parts for speed [OK]
Hint: Fragment caching speeds up page parts loading [OK]
Common Mistakes:
  • Confusing caching with user authentication
  • Thinking it compresses images
  • Assuming it manages database connections
2. Which of the following is the correct syntax to use fragment caching in a Rails view?
easy
A. <% cache 'unique_key' do %> ... <% end %>
B. <% cache do 'unique_key' %> ... <% end %>
C. <% cache 'unique_key' %> ... <% end %>
D. <% cache 'unique_key' { ... } %>

Solution

  1. Step 1: Recall correct fragment caching syntax

    The correct syntax uses cache 'key' do ... end block in ERB.
  2. Step 2: Check each option

    <% cache 'unique_key' do %> ... <% end %> matches the correct block form. Others have wrong block usage or missing do.
  3. Final Answer:

    <% cache 'unique_key' do %> ... <% end %> -> Option A
  4. Quick Check:

    Use cache 'key' do block [OK]
Hint: Remember: cache needs 'do' block syntax [OK]
Common Mistakes:
  • Omitting the 'do' keyword
  • Using braces {} instead of do...end in ERB
  • Placing the key inside the block instead of as argument
3. Given this Rails view code:
<% cache 'post_1' do %>
  <h1>Post Title</h1>
  <p>Post content here.</p>
<% end %>

What happens if the post content changes but the cache is not expired?
medium
A. The page shows an error about stale cache
B. The page shows the old cached content, not the updated post
C. Rails automatically updates the cache with new content
D. The cache is ignored and content always updates

Solution

  1. Step 1: Understand cache behavior on data change

    Fragment cache stores rendered content and does not update unless expired or cleared.
  2. Step 2: Identify effect of not expiring cache

    If cache is not expired, Rails serves the old cached content even if data changed.
  3. Final Answer:

    The page shows the old cached content, not the updated post -> Option B
  4. Quick Check:

    Cache stale without expiry = old content shown [OK]
Hint: Cache must be expired to show updated content [OK]
Common Mistakes:
  • Assuming cache auto-updates on data change
  • Expecting an error when cache is stale
  • Thinking cache is ignored automatically
4. You have this fragment cache in your view:
<% cache 'user_42_profile' do %>
  <p>User profile info</p>
<% end %>

But after updating user data, the cache still shows old info. What is the likely problem?
medium
A. The cache key 'user_42_profile' was not changed or expired after update
B. The cache block syntax is incorrect and causes failure
C. Rails does not support fragment caching for user profiles
D. The view template is missing the cache helper method

Solution

  1. Step 1: Check cache key usage

    Cache keys must change or be expired to reflect updated data.
  2. Step 2: Identify why old data shows

    If key stays same and cache not expired, old cached content remains visible.
  3. Final Answer:

    The cache key 'user_42_profile' was not changed or expired after update -> Option A
  4. Quick Check:

    Cache key unchanged = stale cache shown [OK]
Hint: Expire or change cache key after data updates [OK]
Common Mistakes:
  • Assuming syntax error causes stale cache
  • Believing Rails disables caching for certain views
  • Forgetting to use cache helper in views
5. You want to cache a list of comments for a post, but each comment can be edited independently. Which approach best ensures cache updates correctly?
hard
A. Cache only the post content and ignore comments
B. Cache the entire comments list with a single static key
C. Do not use fragment caching for comments to avoid stale data
D. Cache each comment fragment separately using a unique key per comment

Solution

  1. Step 1: Understand caching granularity

    When parts update independently, caching each part separately allows selective expiration.
  2. Step 2: Apply to comments list

    Caching each comment with a unique key lets you expire only changed comments, keeping others cached.
  3. Step 3: Evaluate other options

    Single static key caches whole list, causing stale data if one comment changes. Avoiding caching loses speed benefits.
  4. Final Answer:

    Cache each comment fragment separately using a unique key per comment -> Option D
  5. Quick Check:

    Separate keys for independent parts = correct caching [OK]
Hint: Cache parts with unique keys for independent updates [OK]
Common Mistakes:
  • Caching entire list causing stale comments
  • Skipping caching due to fear of stale data
  • Ignoring comment updates in cache strategy
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard