ruby-on-rails - Rails 缓存 : Using sweepers for actions which require parameters

标签 ruby-on-rails caching sweeper

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

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 的问题:

  • 它是 ActiveRecord::Base 的继承者吗?
  • 您是否有其他回调返回 false 从而停止链?

  • 网络上的清扫器示例始终将 cache_sweeper 行放在 caches_xxx 行之后。如果这有所作为,我会感到惊讶,但值得一试。

    关于ruby-on-rails - Rails 缓存 : Using sweepers for actions which require parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4794482/

    相关文章:

    ruby-on-rails - 设计 Controller 如何改变布局?

    总结二维数组的函数的缓存行为

    java - 以不同的速率从 InputStream 中多次读取

    ruby-on-rails - Rails 清扫机可以跨不同 Controller 工作吗?

    node.js - npm update -package- 不更新包

    ruby-on-rails - 在 Ruby on Rails 中获取私有(private)方法错误

    javascript - 用于缓存来自 RESTful 服务的搜索结果的优雅方法?

    ruby-on-rails-3 - 文章更新后如何使主页缓存过期?

    ruby-on-rails - Action 缓存未正确过期,即使我可以看到它正在被调用

    ruby-on-rails - 如何从此 instagram json 获取 created_time?