How do I configure the JSON that response_with renders in case of validation errors?

In the 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 validation error, JSON displays in a certain way that does not match the expected client application:

# 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 across the entire application.

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

How do I customize the JSON that respond_with

displays in case of validation errors?

+3


source to share


2 answers


A couple of other ways to customize user alerts

You can just put it on a string:

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



or: you can just link to your [locale file] and post special messages there. 1 :

t(:message)

Hope it helps :)

+3


source


I found a provocative way to get the error hash as one sentence. But not only is it hacked, but it also doesn't match the desired result 100%. I still hope there is a way to do this with a custom serializer or responder.



module ActiveModel
  class Errors
    def as_json(*args)
      full_messages.to_sentence
    end
  end
end

# OUTPUT
{
  "errors": "Price must be greater than 0 and name can't be blank"
}

      

0


source







All Articles