Rails Caching Techniques
Types of Caching in Rails
Caching is a technique used to store frequently accessed data in memory so that it can be retrieved quickly without having to access the database. Rails provides three types of caching techniques by default: fragment caching, page caching, and action caching.
Fragment Caching
Fragment caching stores individual pieces of data in memory, such as a particular view partial or a database query result. This is useful for caching data that is frequently accessed but does not change often, such as the header or sidebar of a website.
Page Caching
Page caching stores entire pages in memory, including the HTML, CSS, and JavaScript. This is useful for caching pages that are frequently accessed and do not change often, such as the home page of a website.
Action Caching
Action caching stores the results of controller actions in memory. This is useful for caching actions that are frequently accessed and do not require any user input, such as the action that displays a list of products.
How to Implement Caching in Rails
To implement caching in Rails, you can use the cache
method. The cache
method takes a key as the first argument and the value to be cached as the second argument. The key is used to identify the cached data, and the value is the data that will be cached.
For example, to cache the header of a website, you can use the following code:
<%= cache("header") do %> My Website
<% end %>
This code will cache the header with the key "header". The header will be cached for the default cache duration, which is 1 hour. You can specify a different cache duration by passing a expires_in
option to the cache
method.
Comments