Ruby-on-rails Rails:渲染 Json 状态问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21896521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: Render Json Status Problems
提问by Morgan
When I
当我
render json: {
error: "No such user; check the submitted email address",
status: 400
}
and then do my tests and check for
然后做我的测试并检查
response.code
I get 200 rather than 400
我得到 200 而不是 400
I'm sure the answer to this absurdly simple, but I've been looking for an hour and cannot seem to get this working. I could just parse the Json and then check the status code...but isn't there a way to get response.code to return the status? I understand that technically it was a success and I assume that's why the response.code is returning 200, but I was using Jbuilder before where I could directly impact the code returned.
我确信这个问题的答案非常简单,但我一直在寻找一个小时,似乎无法让它发挥作用。我可以解析 Json 然后检查状态代码……但是没有办法让 response.code 返回状态吗?我知道从技术上讲它是成功的,我认为这就是 response.code 返回 200 的原因,但我在使用 Jbuilder 之前可以直接影响返回的代码。
回答by Richard Jordan
You have created the json there, which will be returned, and in that json will be an identification of the status - 400. However, that's not telling Rails to send the 400 status in the header.
您已经在那里创建了 json,它将被返回,并且在该 json 中将是状态的标识 - 400。但是,这并没有告诉 Rails 在标头中发送 400 状态。
You could do:
你可以这样做:
render json: {
error: "No such user; check the submitted email address",
status: 400
}, status: 400
Or something like
或者类似的东西
payload = {
error: "No such user; check the submitted email address",
status: 400
}
render :json => payload, :status => :bad_request
You can use either the symbol :bad_request or the status number 400.
您可以使用符号 :bad_request 或状态编号 400。

