[英]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
: 在控制器中,我想用
respond_with
替换if..render..else..render
:
# 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: 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"
]
}
}
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 . 我正在使用响应者gem ,我已经读过它可以自定义响应器和序列化器 。 But how do the pieces fit together?
但这些碎片如何组合在一起?
How to customize the JSON that respond_with
renders in case of validation errors? 如何在验证错误的情况下自定义
respond_with
呈现的JSON?
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 :
1 :
t(:message)
Hope this helps :) 希望这可以帮助 :)
I found a provisory way to get the errors hash as a single sentence. 我找到了一种将错误哈希作为单个句子获取的附带方法。 But not only is it hackish, but it also does not match the desired output 100%.
但它不仅是hackish,而且还与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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.