首页 > 解决方案 > 如何判断哪些关联模型未通过我的 ActiveRecord 验证?

问题描述

假设我有以下型号:

class Race < ApplicationRecord
  has_many :horses
end

class Horse < ApplicationRecord
  belongs_to :race
  validates :name, presence: true
end

现在使用我的 REST API,我正在创建一个Race对象并关联多匹马。其中一匹马未能通过验证,这增加了错误。

添加错误意味着向errors.detailsand中添加条目errors.messages,其中errorsRace模型的一个字段。这两个字段都是散列,分别horses.name作为键和错误和错误消息的详细信息作为值。

我正在寻找一种方法来查找哪些关联Horse模型未通过验证,以便我可以提供全面的错误消息。一个引用、id 甚至一个索引就足够了。

标签: ruby-on-railsrestvalidationactiverecorderror-handling

解决方案


race = Race.create race_params
race.errors.messages
=> {'horses.name' => ['Can't be blank']}
race.horces[0].errors.messages
=> {'name' => ['Can't be blank']}

要获取错误记录,只需过滤 race.horses

with_error = race.horses.select{|h| h.errors.messages.present?}
index = race.horses.index( with_error[0] )

推荐阅读