return 嵌套模型验证错误的更好方法如 Rails 中的 json?

Better way to return validation errors for nested models as json in Rails?

我有class订单,可以内容条目。每个条目可以是复杂类型,并且由另一个条目组成。

class Order < ActiveRecord::Base
  accepts_nested_attributes_for :entries
end

class Entry < ActiveRecord::Base
  accepts_nested_attributes_for :members, allow_destroy: true
end

在表单中,我使用 fields_for

在表单中生成了 rails 个字段
<input autocomplete="off" class="string required form-control" id="order_entries_attributes_1459329286687_members_attributes_1459329286739_title" name="order[entries_attributes][1459329286687][members_attributes][1459329286739][title]" placeholder="Наименование" type="text">

所以,我提交了一份订单,例如有 2 个条目和 5 个验证错误的成员(2 个没有标题的成员),它传递给控制器​​

class OrdersController
  def update
    if @order.update(order_params)
      render json: @order
    else
      render json: @order.errors, status: :unprocessable_entity
    end
  end
end

它return是我这个

{"entries.members.title":["cant be blank"]}

问题是我找不到其中的哪个条目和哪个成员有验证错误,这就是为什么我不能突出显示此字段的原因。此外,它合并了类似的错误。这就是问题。

提交时我传递了唯一索引(在名称属性中),并且 rails 正确地使用它来创建嵌套模型,如果错误响应包含此索引就更好了。

是否有任何其他方法可以 return 来自服务器的良好索引错误,并使用 rails 作为 api 用于 json 而不痛苦?

已更新为与 Rails 嵌套参数

具有相同的格式
render json: {
  order: {
    entries: @order.entries.enum_for(:each_with_index).collect{|entry, index|
      {
        index => {
          id: entry.id,
          errors: entry.errors.to_hash,
          members: entry.members.enum_for(:each_with_index).collect{|member, index|
            { 
              index => {
                id: member.id,
                errors: member.errors.to_hash
              }
            } unless member.valid?
          }.compact
        }
      } unless entry.valid?
    }.compact
  }
}

您应该得到 JSON 回复,例如:

{
  order: {
    entries: [
      0: {
        id: 1, # nil, if new record
        errors: {},
        members: [
          0: {
            id: 7, # nil, if new record
            errors: {
              title: ["cant be blank"]
            }
          },
          1: {
            id: 13, # nil, if new record
            errors: {
              title: ["cant be blank"]
            }
          }
        ]
      }
    ]
  }
}

P.S。也许其他人知道一种 rails 集成的方式来做到这一点。否则,我会说这可能是 git 中 Rails 的一个很好的功能请求。