Rails4 jbuilder 总是返回状态码 200,即使我放了其他状态码 [英] Rails4 jbuilder always return status code 200, even if I put other status code
问题描述
我构建了一个 json 视图以在 rails4 应用程序的 ajax 调用之一中返回 json.我已经使用了这里建议的想法https://stackoverflow.com/a/12832116/1560470
I built a json view to return json in one of ajax call in rails4 app. I have used the idea suggested here https://stackoverflow.com/a/12832116/1560470
但我总是得到 200 的状态码,即使我强制执行其他状态码.
But I always keep getting status code as 200, even if I enforce other status code.
我在 view/managers/create.json.jbuilder 中的 jbuilder 视图如下所示:
My jbuilder view in view/managers/create.json.jbuilder looks as follows:
if @manager.errors.messages.any?
envelope(json, :unprocessable_entity, @manager.errors.messages) do
json.success false
end
else
envelope(json, :created) do
json.success true
end
end
我的应用程序助手lloks如下:
My application helper lloks as follows:
module ApplicationHelper
def envelope json, status, errors
json.status status
json.data do
yield if block_given?
end
json.errors errors
end
end
我的控制器如下:
def create
@manager = Manager.new manager_params
@saved = ( @manager.valid? && @manager.save )
end
你可以看到即使我在我的 jbuilder 视图中将 status
参数值作为 :unprocessable_entity
传递,每次仍然响应返回 200.即使我使用任何状态代码,它总是返回 200.状态代码定义在 http://guides.rubyonrails.org/layouts_and_rendering.html
You can see even I am passing status
params value as :unprocessable_entity
in my jbuilder view, still response comes back as 200 every time. Even I use any status code, it always return 200. Status codes are defined at http://guides.rubyonrails.org/layouts_and_rendering.html
推荐答案
我遇到了同样的问题,我发现成功调用 render 后跟您想要发出的任何状态.在 create
的底部放置以下内容
I had the same issue, I found success with a call to render followed by whatever status you want to issue. At the bottom of create
put the following
render status: 400
参考:https://stackoverflow.com/a/28144206/3826642
您可以将逻辑从该信封方法移动到 jbuilder 模板,以便将状态直接从控制器传递到视图.
You can move the logic from that envelope method to the jbuilder template so you're passing status directly from controller to the view.
您在信封方法中的状态只会在呈现的 json 中,它不是服务器发送的 http 响应状态代码,而在呈现方法中的状态代码是
That status you have in the envelope method will only be in the json that is rendered, it's not a http response status code sent by the server whereas as the one in the render method is
这篇关于Rails4 jbuilder 总是返回状态码 200,即使我放了其他状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!