2013-02-25 81 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