RailsCasts Pro episodes are now free!
Learn more or hide this
There is a newer version of this episode, see the revised episode.
Resources
cache_sweeper :product_sweeper, :only => [:create, :update, :destroy]
class Product < ActiveRecord::Base def self.find_recent find(:all, :order => 'released_at desc', :limit => 10) end end
config.action_controller.perform_caching = true
config.load_paths << "#{RAILS_ROOT}/app/sweepers"
class ProductSweeper < ActionController::Caching::Sweeper observe Product def after_save(product) expire_cache(product) end def after_destroy(product) expire_cache(product) end def expire_cache(product) expire_fragment 'recent_products' end end
<% cache 'recent_products' do %> <div id="recent_products"> <h2>Recent Products</h2> <ul> <% for product in Product.find_recent %> <li><%= link_to h(product.name), product %></li> <% end %> </ul> </div> <% end %>