2013-03-05 38 views
1

我試圖提供一個自定義的404響應在rails中,但我不知道如何給:respond_with函數的狀態。使用respond_with服務404?

我知道有render,我可以做這樣的事情:

render :status => :not_found, :json => {:response =>"There weren't any results"} 

我怎麼可以做這樣的事情與respond_with?有沒有辦法用respond_with設置狀態碼?

我使用respond_with的唯一原因是,據我的理解,當您開始使用respond_to時,使用respond_with是正確的協議。如果這是不正確的,我應該使用render,請讓我知道!

回答

5

參見the docs; respond_with需要:status作爲選項。

respond_with(@user, status: :not_found) do |format| 
    format.json { response: "There weren't any results" } 
end 
+0

對不起。我不確定我錯過了你的答案。非常感謝!那很完美。不幸的是,我是ruby的新手,我在文檔中尋找'respond_with'而不是'Responder'。這正是我需要的。 – RileyE 2013-03-06 15:38:58

1

而是一套在響應特定的404種狀態,你可以只提出一個ActiveRecord::RecordNotFound例外,它有同樣的效果。 Check it here

+0

對不起,任何混淆,但'ActiveRecord :: RecordNotFound'不允許自定義響應。我知道這個問題在我的問題上並不是很清楚,但是我很欣賞這種迴應,因爲它有助於瞭解。謝謝! – RileyE 2013-03-06 15:40:19

+0

提升'ActiveRecord :: RecordNotFound'的問題是它將被記錄爲異常,並且取決於您的API,它不是一個例外。也許你只想檢查資源是否存在。對於例如如果購物車不存在(not_found),則創建它,基本上嘗試get來顯示,如果它返回not_found,則創建一個帖子。 – 2013-06-07 20:39:06