rails缓存实例

给新闻添加页面缓存、以及更新时缓存清除:
class NewsController < ApplicationController
  caches_page :show, :index
  cache_sweeper :news_sweeper, :only => [:create, :update, :destroy]
  
  def index
    list
    render :action => 'list'
  end

  def show    
    @news = News.find(params[:id])
    render :layout=>"main"
  end

  def create
  end

  def update
  end

  def destroy
    News.find(params[:id]).destroy
    redirect_to :action => 'list'
  end

end


在environment中配置:
config.active_record.observers = :news_sweeper


定义NewsSweeper类:
class NewsSweeper < ActionController::Caching::Sweeper
  observe News
  
  def after_save(news)
    clear_news_cache(news)
  end
  
  def after_destroy(news)
    clear_news_cache(news)
  end
  
  def after_update(news)
    clear_news_cache(news)
  end
  
  def clear_news_cache(news)
    expire_page :controller => :news, :action => :index
    expire_page :controller => :news, :action => :show, :id=>news
    expire_page :controller => :main, :action => :news, :id=>news
  end
end


相关技术连接参考: [/url]http://www.ibm.com/developerworks/cn/web/wa-rails1/

你可能感兴趣的:(cache,Rails)