我正在尝试使用清扫器来处理我的页面刷新。对于刷新索引操作等,一切正常……但我似乎无法解释页面参数。如果有人能告诉我下面的代码有什么问题,我将不胜感激:
Controller :
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
最佳答案
如果我们假设您复制并粘贴了代码,那么您的代码中也有错别字。由于您没有被 Rails 标记为错误,因此我们可以假设没有调用清扫器。 (即没有调用 after_update )。我会添加一些记录器消息以验证情况确实如此。
关于 Post 的问题:
网络上的清扫器示例始终将 cache_sweeper 行放在 caches_xxx 行之后。如果这有所作为,我会感到惊讶,但值得一试。
关于ruby-on-rails - Rails 缓存 : Using sweepers for actions which require parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4794482/