简体   繁体   English

Rails JSON API-JSON不包含错误

[英]Rails JSON API - json doesn't contain errors

I am rendering an array of ActiveRecord items. 我正在渲染ActiveRecord项目的数组。 Each of them has passed through valid? 他们每个人都通过了valid? method - so the errors are already defined. 方法-因此错误已经定义。 I render the array like this: 我这样渲染数组:

render json: array_of_objects

I have ActiveModelSerializers.config.adapter = :json_api set. 我有ActiveModelSerializers.config.adapter = :json_api设置。

But the outcome json lacks errors - it contains only the data of objects. 但是结果json没有错误-它仅包含对象的数据。

How can I retrieve json (of each one by one or all at once) items with the errors included? 如何检索包含错误的json(每一项或全部一次)项目?

The JSON API specification is very fuzzy when it comes to how validation errors should be handled: 关于如何处理验证错误,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. 当服务器针对单个请求遇到多个问题时,应在响应中使用最普遍适用的HTTP错误代码。 For instance, 400 Bad Request might be appropriate for multiple 4xx errors or 500 Internal Server Error might be appropriate for multiple 5xx errors. 例如,400 Bad Request可能适用于多个4xx错误,或者500 Internal Server Error可能适用于多个5xx错误。

Error objects can be included - but they should be included at the top level of the document: 可以包含错误对象-但应将其包含在文档的顶层:

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. 错误对象必须以JSON API文档顶层中的错误为键的数组形式返回。

ActiveModel::Serializers JSON API Adapter does not provide error object handling as it would be far to complex to handle the various use cases. ActiveModel :: Serializers JSON API适配器不提供错误对象处理,因为处理各种用例非常复杂。

Especially your case as you seem to be creating/modifying several records at once. 特别是您的案例,因为您似乎要一次创建/修改多个记录。 In the case of creating its especially tricky since you need to link the error to the attribute in the input that caused the error since there is no id to point to. 在创建它特别棘手的情况下,因为由于没有ID指向,所以需要将错误链接到导致错误的输入中的属性。

You can possibly roll your own serializer: 您可以滚动自己的序列化器:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM