Caching in Rails

This Post I am going to explain how to achieve the caching mechanism in Rails

There are three types of caching techniques
  1. Page Caching
  2. Action Caching
  3. Fragment Caching (Default in rails)
Rails 4 
    Static page caching and action caching is removed from core in  Rails 4.0

If the user wants to enable  page and action caching, you will need to add actionpack-page_caching and actionpack-action_caching to your Gemfile.(removed from core in Rails 4.0)

Note
 Rails caching is disabled by default in the development environment. Make sure you have below the parameter value below set to true in your Rails app config file.

#Inside config/environments/development.rb
config.action_controller.perform_caching = true

Rails caching is enabled in production mode by default.

Page Caching :
In Rails Page Caching, whenever a request is sent to the server, the Rails server would check for the cached page and if that exists it would be served.
 If it does not exist, Rails server generates the page & cache it. Hence the Rails app won’t have to generate it again during the next request.

Page caching is an approach to caching where the entire action output of is stored as a HTML file that the web server can serve without going through Action Pack.
Real time Usage in applications

Content management systems – including weblogs and wikis – have many pages that are a great fit for this approach, but account-based systems where people log in and manipulate their own data are often less likely candidates.


Example:

class HomeController < ApplicationController
  caches_page :index

  def index


  end

end

To expire the cache when an update is made, we will have to call

an expire_page helper method.

def update
       expire_page :action => index
end

Here it is assumed that update action is being called when the page is updated. expire_page inside the action makes sure the cached page is purged & new cached page is created during the next call to profile action.
This type of caching in Rails is lightning fast, but one main disadvantage of this is that this can’t be used for caching every page. As the requests don’t go to the Rails app, the authentication and access restrictions using before_filter won’t work if page caching is used.

The above example is probably the wrong usage of the Rails page cache. You can see that page served by ‘profile’ action has dependency on the current_user (assume it to be logged in user).


Let’s say user_1 is the first user to view the page. The page will be generated & cached with contents for user_1 . If user_2 tries to go to his profile page, he will see user_1 content on it. This is plain wrong  .