【发布时间】:2017-06-12 15:52:19
【问题描述】:
在控制器中,我想将if..render..else..render 替换为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
respond_with 的问题在于,如果出现验证错误,JSON 会以不符合客户端应用程序期望的特定方式呈现:
# 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"
]
}
}
产品、价格和名称是示例。我希望整个应用程序都有这种行为。
我正在使用responders gem,并且我已阅读可以自定义响应者和serializers。但是这些部分是如何组合在一起的呢?
如何自定义respond_with在出现验证错误时呈现的JSON?
【问题讨论】:
标签: ruby-on-rails json active-model-serializers respond-with responders