Last Updated: February 25, 2016
·
685
· neutralino1

Rails: page and action caching

If some of your pages rarely change, it is wise to activate caching on them. To do so is very easy in Rails. Simply add the following snippet in the appropriate controller:

class PostsController < ApplicationController

  caches_page :index

  def index
    # do something
  end

end

If your controller has some sort of before_filter to control the access the the resource, use caches_action instead. Then your callbacks will be run (e.g. `beforefilter :authenticateuser!).

The file posts.html will be created the first time the page is visited, stored in /public and served on every new request on the resource.

URL parameters (e.g. /posts?page=2) are not used to generated the cached page. Make sure you include the parameters you want to use for caching in the path itself: /posts/page/2.

To expire a cached page, simple do

expire_action :action => :index

Happy caching!