Rails缓存:使用清扫器进行需要参数的操作

时间:2011-01-25 14:15:04

标签: ruby-on-rails caching sweeper

我正在尝试使用清扫工来处理页面刷新。为了刷新索引操作等等一切正常......但我似乎无法清理器解释页面参数。如果有人能告诉我下面的代码有什么问题,我会非常感激:

控制器:

class PostsController < ApplicationController
  load_and_authorize_resource
  cache_sweeper :post_sweeper, :only => [:create, :update, :destroy]
  caches_page :index
  caches_page :show
  caches_action :edit, :new

  # This refreshes cache correctly
  def index
    @posts = Post.all
  end

#这会创建缓存,但不会刷新(永远)。如果我将expire_page命令直接放入动作(而不是扫描程序),它可以正常工作

def update
    @post = Post.find(params[:id])
    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = t(:post_updated)
        format.html { redirect_to(@post) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

清道夫:

class PostSweeper < ActionController::Caching::Sweeper
  observe Post

  def after_create(record)
    expire_cache_for_index(record)
  end

  def after_update(record)
    expire_cache_for_index(record)
    expire_cache_for_post(record)
    expire_cache_for_edit(record)
  end

  def after_destroy(record)
    expire_cache_for_index(record)
    expire_cache_for_post(record)
    expire_cache_for_edit(record)
  end

  private
  def expire_cache_for_index(record)
    expire_page :controller => 'posts', :action => 'index'
  end

  def expire_cache_for_post(record)
    expire_page :controller => 'posts', :action => 'show', :id => record.id
  end

  def expire_case_for_edit(record)
    expire_action :controller => 'posts', :action => 'edit', :id => record.id
  end

end

1 个答案:

答案 0 :(得分:1)

如果我们假设您复制并粘贴了代码,那么拼写错误也在您的代码中。由于您没有被Rails标记为错误,我们可以假设没有调用扫描程序。 (即没有调用after_update)。我会添加一些记录器消息来验证确实是这种情况。

问题是关于帖子:

  1. 它是ActiveRecord :: Base的继承人吗?
  2. 您是否有其他返回错误并因此停止链接的回调?
  3. 网上的清扫器示例始终将cache_sweeper行放在 caches_xxx行之后。如果这有所不同,我会感到惊讶,但值得一试。