1nap8w
Last Updated: February 25, 2016
·
440
· neutralino1
981494 10151466984546915 1613396205 o

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!

Say Thanks
Respond