【问题标题】:Rails action caching refresh after expireRails 动作缓存过期后刷新
【发布时间】:2013-02-10 20:29:41
【问题描述】:

我希望过期,然后使用可公开访问的端点为控制器操作刷新缓存。

目前在我的应用程序中,/all 返回缓存的 json,并且 /update 使缓存过期。 您可以在下面看到现有的相关代码。 我想做的不仅是使缓存过期,而且还强制刷新。 所以,我的问题是:

有没有办法在动作缓存过期后启动它的刷新,而不点击动作?

如果答案是否定的(正如我开始怀疑的那样),那么最好的方法是什么?我需要更新操作来返回 HTTP 200 状态,而不是 301 重定向,因此仅重定向到 /all 不是一个选项。

供应商控制器

caches_action :all, :expires_in=>2.weeks

....

def all 
  respond_to do |format|
    format.json { render :json => Vendor.all }
    format.html { render :json => Vendor.all }
  end
end


....

def update
  render :nothing => true
  expire_action :action => :all
end

【问题讨论】:

    标签: ruby-on-rails-3 caching action-caching


    【解决方案1】:

    你应该使用write_fragment

    def update
      render :nothing => true
      expire_action :action => :all
    
      cache_path = ActionCachePath.new(self, {:action => :all}, false).path
      write_fragment(cache_path, render_to_string(:json => Vendor.all))
    end
    

    可能有帮助的来源:

    【讨论】:

    • 感谢您的回复。但是,有两个担忧。 1. cache_page 不写入磁盘,而action cache 使用memcache? 2. 由于我在控制器中直接渲染 json(可以说不是最好的模式),没有vendors/all 的模板,因此它不知道如何将其渲染为字符串。想法?感谢您的帮助。
    • @manderson 我没有注意到你在使用cache_action。我已经更新了我的答案,改为使用write_fragment,它可能会起作用。我添加了指向动作缓存的 Rails 源的链接以获取更多信息。对于第2点,直接使用render_to_string(:json => Vendor.all)。它应该可以工作。
    • 太棒了!非常感谢你的帮助。 write_fragment 完全有意义。如果没有您的代码,我将无法编写 cache_path 行,但我的 rails-fu 正在增长。
    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2011-08-06
    • 2013-09-14
    • 1970-01-01
    相关资源
    最近更新 更多