在ActiveModel :: Serializer中序列化错误哈希 [英] Serializing the errors hash in ActiveModel::Serializer
问题描述
我正在使用ActiveModel :: Serializer为我的API自定义JSON响应.在大多数情况下,这种方法都可以正常工作,除非无法成功保存模型.
I'm using ActiveModel::Serializer to customize the JSON responses for my API. This works fine in most cases, except when it fails to save a model successfully.
例如,
def create
def create
book = Book.new(book_params)
book.save
respond_with book, location: nil
end
end
据我所知,response_with操作基本上将执行如下所示的代码(以生成响应).
As I understand it, the respond_with action will basically execute code that looks something like this (in order to generate the response).
if resource.errors.any?
render json: {:status => 'failed', :errors => resource.errors}
else
render json: {:status => 'created', :object => resource}
end
这确实与我看到的内容匹配-如果我的模型无法成功保存,我将看到错误哈希作为响应.但是,我不知道如何为错误哈希指定序列化器.
This does match up with what I'm seeing - if my model fails to save successfully I see the errors hash as the response. However, I can't figure out how I specify a serializer for the errors hash.
我尝试定义ErrorsSerializer,如果我运行
I tried defining an ErrorsSerializer and if I run
ActiveModel::Serializer.serializer_for(book.errors)
在控制台中,似乎找到了我的序列化器,但没有被使用.在这种情况下如何自定义JSON响应?
in the console it seems to find my serializer, but it doesn't get used. How do I customize the JSON response in this scenario?
推荐答案
我相信在这种情况下的问题是,对于failed
状态,您不会像对象一样调用render
,例如created
状态.
I believe that the problem in this case is that for the failed
status you won't call render
with an object, like for created
status.
您可以在调用render
时使用自定义的序列化程序,在这种情况下,您可能可以使用类似的
You can use a custom Serializer when calling render
, for this case you can probably use something like
if resource.errors.any?
render serializer: ErrorSerializer, json: {:status => 'failed', :errors => resource.errors}
else
render json: {:status => 'created', :object => resource}
end
尝试一下,让我们知道结果吧:)
Give it a try and keep us informed of the result :)
这篇关于在ActiveModel :: Serializer中序列化错误哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!