Reputation: 3912
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
Upvotes: 1
Views: 3594
Reputation: 1335
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
Upvotes: 2