Introduction to Rails Caching
Introduction
Reasonable use of caching can greatly improve a website’s performance, making it an indispensable part of performance optimization.
Caching
Model-layer caching
Through manual configuration, you can store selected query results in the corresponding cache system.
1
2
3Rails.cache.fetch('all_products', expires_in: 1.days) do
Product.all.to_a
endMake sure to verify that the returned result is the final result set.
Controller-layer caching
Action caching
Caches the Action response, implemented with the help of Fragment Cache and callbacks.
Various verification mechanisms can be added via
before_action.1
2before_action :authentication, only: :show
cache_action :show, expires_in: 1.hourThis method was removed in Rails 4, but it can be re-enabled through a Gem.
Page caching
Caches the page as a static page; it cannot perform authentication or similar checks.
1
2
3class ProductsController < ActionController
caches_page :index
endThis method was removed in Rails 4, but it can be re-enabled through a Gem.
View-layer caching
SQL caching
This is a built-in feature of the Rails framework; it caches the result set of each query.
1
2
3
4
5
6
7
8class ProductsController < ActionController
def index
# First Query
@products = Product.all
# Second Query (Cache)
@products = Product.all
endWhen the second query runs, it reads the result set cached in memory by the first query directly.
Tips: The cache is valid for the lifetime of the action.
Configuration
1 | # Enable caching |