3

我正在尝试在 Rails 中提供自定义 404 响应,但我不确定如何将 :status 赋予respond_with函数。

我知道render,我可以做这样的事情:

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

我怎么能做这样的事情respond_with呢?有没有办法设置状态码respond_with

我使用的唯一原因respond_with是,据我了解,respond_with当您开始使用respond_to. 如果这不正确并且我应该使用render,请告诉我!

4

2 回答 2

7

请参阅文档;作为一种选择respond_with:status

respond_with(@user, status: :not_found) do |format|
  format.json { response: "There weren't any results" }
end
于 2013-03-05T23:43:17.010 回答
2

而不是在您的响应中设置特定的 404 状态,您可以只引发一个ActiveRecord::RecordNotFound异常并且它具有相同的效果。在这里检查

于 2013-03-06T12:29:05.593 回答