How to Use Caching in Rails

In and by itself, caching is not very difficult in Rails. The most immediately useful type of caching is action caching (because you can combine it with authentication). You can just use call caches_action in your controller file, giving the action to be cached as an arugment:

class GuestsController < ApplicationController

  caches_action :show

  ## ... Other controller code ...
end

Now, if you've got your config/environments/development.rb set to:

config.action_controller.perform_caching             = true

- the screen for the show action will be cached immediately, once you've restarted your webserver. To empty the cache, use a sweeper:

class GuestSweeper < ActionController::Caching::Sweeper
  observe Guest

  def after_update(guest)
    expire_action :controller => :show, :action => :show
  end
end  

And call the sweeper in your controller:

class GuestsController < ApplicationController
  
  caches_action :show
  cache_sweeper :guest_sweeper

  ## ... Other controller code ...
end

There are more ways to cache a cat, erm, page, however. Please take a look at Gregg Pollack's excellent series of screencasts on Scaling Rails.


Personal Tools