2010-09-19 25 views
4

在我post_index行動,我產生不同種類的「@posts」之類的..rails fresh_when/stale?使用

def index 
    case params[:listing_type] 
    when "all" 
     @posts = get_all_post_from_memcached 
    when "most_popular" 
     @posts = get_all_most_popular_from_memcached 

     respond_to do |format| 
     format.html 
     format.js #for ajax reqeusts 
     format.xml #for rss etc 
     end 
    end 
end 

##updated 
def index 
    case params[:listing_type] 
    when "all" 
     #the key here is teh same key I used for memcached 
     if stale?(:etag => 'all_posts_key') 
     @posts = get_all_post_from_memcached 
     else 
     head :not_modified and return 
     end 
    when "most_popular" 
     if stale?(:etag => 'most_popular_key') 
     @posts = get_all_most_popular_from_memcached 
     else 
     head :notified and return 
     end 
     respond_to do |format| 
     format.html 
     format.js #for ajax reqeusts 
     format.xml #for rss etc 
     end 
    end 
end 

從我的理解fresh_when需要etag,是如果在不同類型的沒有區別使用的呈現(在我的情況下呈現是不同基於HTML或AJAX)

stale?還需要一個etag幷包圍respond_to代碼塊。

在這種情況下,etag將根據不同的列表類型而有所不同。但是,在這裏可以使用fresh_whenstale?的方式似乎沒有太大的靈活性?

謝謝

更新。我改變了原來的一小塊,現在得到一個雙渲染錯誤,我做錯了什麼,應該「頭:通知並返回」只是返回標題,而不是觸摸respond_to塊?

+1

我有這個錯誤(或類似的),我做了'如果陳舊? @item,public:true respond_to do | format | format.html#show.html.erb format.json {渲染JSON:@item} 結束在動作結束 結束 ' ,而工作,並沒有完全理解爲什麼 – juanpastas 2012-10-29 22:48:59

+0

不能很好格式化評論,對不起。 – juanpastas 2012-10-29 22:50:56

+0

我認爲你很混淆對象和http緩存。陳舊?將簡單地返回一個'304'響應,如果條件成立,則返回一個沒有主體的響應。因此,瀏覽器要求一個頁面,你檢查是否認爲該頁面已經改變,如果沒有,告訴它它沒有(304)。如果你返回一個304,那麼memcached中的內容並不重要,因爲你永遠不會將它呈現給客戶端。 – toxaq 2013-07-20 12:02:56

回答

0

如果您有特殊的響應處理,如show方法中的處理,那麼請使用陳舊?幫手。如果您沒有任何特殊的響應處理,如編輯方法中的處理和使用默認渲染機制(即,您沒有使用respond_to或自己調用渲染),則使用fresh_when。