Joã*_*uza 5 json ruby-on-rails respond-with responders active-model-serializers
在控制器中,我想替换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
Run Code Online (Sandbox Code Playgroud)
问题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"
]
}
}
Run Code Online (Sandbox Code Playgroud)
产品、价格和名称是示例。我希望在整个应用程序中都有这种行为。
我正在使用响应者 gem并且我读过可以自定义响应者和序列化程序。但是这些碎片是如何组合在一起的呢?
如何自定义respond_with在出现验证错误时呈现的 JSON ?
我找到了一种临时方法来将错误哈希作为单个句子获取。但它不仅是 hackish,而且也不能 100% 符合所需的输出。我仍然希望有一种方法可以使用自定义序列化器或响应器来做到这一点。
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"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
695 次 |
| 最近记录: |