Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize the JSON that respond_with renders in case of validation errors?

In a controller, I want to replace if..render..else..render with respond_with:

# Current implementation (unwanted)
def create
  @product = Product.create(product_params)
  if @product.errors.empty?
    render json: @product
  else
    render json: { message: @product.errors.full_messages.to_sentence }
  end
end

# Desired implementation (wanted!)
def create
  @product = Product.create(product_params)
  respond_with(@product)
end

The problem with respond_with is that, in case of a validation error, the JSON renders in a specific way that doesn't fit what the client application expects:

# What the client application expects:
{
  "message": "Price must be greater than 0 and name can't be blank"
}

# What respond_with delivers (unwanted):
{
  "errors": {
    "price": [
      "must be greater than 0"
    ],
    "name": [
      "can't be blank"
    ]
  }
}

Product, price and name are examples. I want this behavior through the entire application.

I am using the responders gem and I've read it's possible to customize responders and serializers. But how do the pieces fit together?

How to customize the JSON that respond_with renders in case of validation errors?

like image 943
João Souza Avatar asked Oct 18 '22 11:10

João Souza


1 Answers

A couple other ways to customize user alerts

You can just put it in line:

render json: { message: "Price must be greater than 0" }

or: You can just reference your [locale file] and put in custom messages there. 1:

t(:message)

Hope this helps :)

like image 179
gwalshington Avatar answered Oct 21 '22 03:10

gwalshington