2014-09-13 49 views
0

我正在使用ETag緩存的Rails(4.1.1)行爲與stale?方法;但它不考慮請求格式。例如:如果/stations.json已被用戶加載,然後他們點擊指向/stations的鏈接,則它們將獲得緩存的JSON響應而不是html。Rails緩存給出了錯誤的響應格式

我做錯了,還是這是一個Rails的bug?

# GET /stations 
# GET /stations.json 
def index 
    @title = "Stations" 
    @last_updated = Station.order("updated_at asc").last 

    if stale?(@last_updated, last_modified: @last_updated.try(:updated_at)) 
    @stations = all_with_latest_observation 
    respond_to do |format| 
     format.html 
     format.json { render json: @stations } 
    end 
    end 
end 
+0

你在哪裏設置你的緩存?顯示你的代碼。 – dddd1919 2014-09-16 02:06:25

+0

@ dddd1919:['stale?'](http://apidock.com/rails/ActionController/Base/stale%3F) – max 2014-09-16 18:05:36

+0

對不起,我不熟悉rails4的功能。看起來像'陳舊'會判斷你的參數來決定是否返回'304',當請求json數據時你會嘗試跳過陳舊嗎? – dddd1919 2014-09-17 01:35:40

回答

0

這似乎是一個bug in ActionPack

我找到了一個解決辦法

class ApplicationController 
    etag { request.format } 
end 

,當然還有規格:

describe StationsController do 
    describe "GET index" do 
    describe "ETag" do 
     before { get :index, format: 'json' } 
     it "should not use the same ETag for different content types" do 
     get :index, format: 'json' 
     first_response = response.headers.clone 
     get :index, format: 'html' 
     expect(first_response['ETag']).to_not eq (response.headers['ETag']) 
     end 
    end 
    end 
end 
1

我認爲你應該添加鍵:etag,當你調用陳舊嗎?方法。

# GET /stations 
# GET /stations.json 
def index 
@title = "Stations" 
@last_updated = Station.order("updated_at asc").last 

if stale?(etag: @last_updated, last_modified: @last_updated.try(:updated_at)) 
    @stations = all_with_latest_observation 
    respond_to do |format| 
    format.html 
    format.json { render json: @stations } 
    end 
end 
end 

然後讓我們看看會發生什麼!

+0

這似乎解決了這個問題,不知道爲什麼自[stale?](https://github.com/rails/rails/blob/b40bd16b7b0810b9d5621339f243c4a9569ceb96/actionpack/lib/action_controller/metal/conditional_get.rb#L136)可以採取一個資源作爲第一個參數。 – max 2014-09-18 12:03:18