Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Render Json Status Problems

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

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.

like image 635
Morgan Avatar asked Feb 20 '14 01:02

Morgan


1 Answers

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.

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.

like image 110
Richard Jordan Avatar answered Nov 07 '22 13:11

Richard Jordan