Andrey Inishev Andrey Inishev - 3 months ago 50
JSON Question

Rails: validation error codes in JSON

So, I am writing Rails web application which has JSON API for mobile apps. For example, it sends POST JSON request to to create order.

{id: 1, order: { product_name: "Pizza", price: 10000}}

In case of validation errors I can response with HTTP 422 error code and order.errors.full_messages in json. But it seems better for me to have specific error code in JSON response. Unfortunately, it seems like Rails does not provide ability to set error code for validation error. How to solve this problem?


You can pass a custom status code by using the status option when rendering the response.

def create
  @order = ...

    render json: @order
    render json: { message: "Validation failed", errors: @order.errors }, status: 400

I usually tend to return HTTP 400 on validation errors. The message is a readable status response, the errors are also attached.

This is a respons example

    message: "Validation failed",
    errors: [

You can also embed additional attributes.