简体   繁体   English

使用respond_with来服务404?

[英]Using respond_with to serve 404?

I'm trying to serve up a custom 404 response in rails, but I'm not sure how to give the :status to a respond_with function. 我正在尝试在rails中提供自定义404响应,但我不确定如何将:status赋予respond_with函数。

I know with render , I can do something like this: 我知道render ,我可以这样做:

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

How can I do something like that with respond_with ? 如何使用respond_with做类似的事情? Is there even a way to set status codes with respond_with ? 有没有办法用respond_with设置状态代码?

The only reason I'm using respond_with is because, to my understanding, it is proper protocol to use respond_with when you've started with respond_to . 我使用的唯一原因respond_with是因为,我的理解,它是使用适当的协议respond_with当你开始使用respond_to If that isn't correct and I should be using render , please let me know! 如果这不正确,我应该使用render ,请告诉我!

See the docs ; 查看文档 ; respond_with takes :status as an option. respond_with接受:status作为选项的:status

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

Instead of set a specific 404 status in your response, you could just raise a ActiveRecord::RecordNotFound exception and it has the same effect. 您可以只提出一个ActiveRecord::RecordNotFound异常,而不是在您的响应中设置特定的404状态,它具有相同的效果。 Check it here 在这里查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM