0
0
Ruby on Railsframework~3 mins

Why Fragment caching in Ruby on Rails? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your website could remember parts of pages to load instantly every time?

The Scenario

Imagine a busy website where every page has many parts that take a long time to load, like lists of products or user comments. Every time someone visits, the server has to build all these parts from scratch.

The Problem

Building each part every time is slow and makes the website feel laggy. It also wastes server power and can cause delays when many users visit at once.

The Solution

Fragment caching lets you save pieces of a page after building them once. Then, when the same piece is needed again, the server quickly reuses the saved version instead of rebuilding it.

Before vs After
Before
render partial: 'comments', locals: { comments: @comments } # builds comments every time
After
cache('comments_section') { render partial: 'comments', locals: { comments: @comments } } # saves and reuses comments HTML
What It Enables

This makes pages load faster and reduces server work by reusing parts that don't change often.

Real Life Example

On a blog, the list of recent posts rarely changes. Fragment caching saves that list so visitors see it instantly without the server rebuilding it each time.

Key Takeaways

Building page parts every time is slow and costly.

Fragment caching saves and reuses pieces of pages.

This speeds up websites and reduces server load.