Rails JSON API - json 不包含错误

Rails JSON API - json doesn't contain errors

我正在呈现一组 ActiveRecord 项目。他们每个人都通过了 valid? 方法 - 所以错误已经被定义了。 我这样渲染数组:

render json: array_of_objects

我已经ActiveModelSerializers.config.adapter = :json_api设置了。

但结果 json 没有错误 - 它只包含对象的数据。

如何检索包含错误的 json 项(每一项一项或一次全部)?

JSON API 规范在如何处理验证错误方面非常模糊:

A server MAY choose to stop processing as soon as a problem is encountered, or it MAY continue processing and encounter multiple problems. For instance, a server might process multiple attributes and then return multiple validation problems in a single response.

When a server encounters multiple problems for a single request, the most generally applicable HTTP error code SHOULD be used in the response. For instance, 400 Bad Request might be appropriate for multiple 4xx errors or 500 Internal Server Error might be appropriate for multiple 5xx errors.

可以包含错误对象 - 但它们应该包含在文档的顶层:

Error objects provide additional information about problems encountered while performing an operation. Error objects MUST be returned as an array keyed by errors in the top level of a JSON API document.

ActiveModel::Serializers JSON API 适配器不提供错误对象处理,因为处理各种用例会非常复杂。

尤其是你的情况,因为你似乎同时 creating/modifying 多条记录。在创建它的情况下特别棘手,因为您需要 link 输入中导致错误的属性的错误,因为没有要指向的 id。

您可以推出自己的序列化程序:

class PostSerializer < ActiveModel::Serializer
  attributes :title, :body, :errors

  def errors
    object.errors.full_messages if object.errors.any?
  end
end