2013-02-25 94 views
2

我期待过期,然后刷新控制器操作缓存使用公共可访问的端点。Rails行动缓存刷新后过期

在我的应用程序当前,/所有返回缓存的json和/ update到期缓存。 您可以在下面看到现有的相关代码。 我想要做的不仅是过期缓存但强制刷新。 所以,我的问题是:

是否有办法启动刷新行动缓存到期后,没有触及行动?

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

VendorsController

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 

回答

3

您应该使用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 

来源,可以帮助:

+0

感谢您的回复。 但是,有两个问题。 1. Cache_page不写入磁盘,而操作缓存使用memcache? 2.由于我在控制器中正确渲染json(可能不是最好的模式),因此没有'vendors/all'的模板,所以它不知道如何将它渲染为字符串。 想法?谢谢你的帮助。 – manderson 2013-02-26 18:28:17

+0

@manderson我没有注意到你正在使用'cache_action'。我已经更新了我的答案,而不是使用'write_fragment',它可能会起作用。我已经添加了关于动作缓存的rails源的链接以获取更多信息。对于第2点,直接使用'render_to_string(:json => Vendor.all)'。它应该工作。 – Baldrick 2013-02-26 22:43:33

+0

太棒了!非常感谢你的帮助。 write_fragment完全有意义。如果没有你的代码,我将无法编写cache_path行,但我的rails-fu正在增长。 – manderson 2013-02-27 16:28:53