Rails4 jbuilder always return status code 200, even if I put other status code

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

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

But I always keep getting status code as 200, even if I enforce other status code.

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 

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 

My controller is as follows:

def create     @manager = Manager.new manager_params     @saved = ( @manager.valid? && @manager.save ) end 

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

回答1:

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 

Reference: https://stackoverflow.com/a/28144206/3826642

You can move the logic from that envelope method to the jbuilder template so you're passing status directly from controller to the view.

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!