0
0
Ruby on Railsframework~5 mins

Page and action caching in Ruby on Rails

Choose your learning style9 modes available
Introduction

Page and action caching help your website load faster by saving copies of pages or actions. This means the server can quickly show saved content instead of making it again every time.

When you want to speed up pages that don't change often, like a homepage or about page.
When many users visit the same page and you want to reduce server work.
When you want to save time by not running the same code repeatedly for each visitor.
When you want to improve user experience by showing pages faster.
When your site has actions that produce the same result for many users.
Syntax
Ruby on Rails
caches_page :index

caches_action :show

caches_page saves the entire HTML output of a page.

caches_action saves the result of a controller action, which can be more flexible.

Examples
This saves the full HTML of the index page so it loads instantly next time.
Ruby on Rails
class ProductsController < ApplicationController
  caches_page :index
end
This saves the output of the show action, speeding up loading for each article.
Ruby on Rails
class ArticlesController < ApplicationController
  caches_action :show
end
You can use both caching types in one controller for different actions.
Ruby on Rails
class HomeController < ApplicationController
  caches_page :welcome
  caches_action :dashboard
end
Sample Program

This example caches the full HTML of the posts index page. When users visit again, Rails serves the saved page quickly without running the index code again.

Ruby on Rails
class PostsController < ApplicationController
  caches_page :index

  def index
    @posts = Post.all
  end
end
OutputSuccess
Important Notes

Page caching works best for static content but is less flexible if you need to show different content to different users.

Action caching allows filters and authentication to run before serving cached content.

Remember to expire caches when content changes, so users see fresh data.

Summary

Page caching saves the full HTML page for fast loading.

Action caching saves the controller action output and can run filters before serving.

Use caching to improve speed but manage cache expiration carefully.