如何判断哪个关联模型未通过ActiveRecord验证?

时间:2019-06-30 21:49:41

标签: ruby-on-rails rest validation activerecord error-handling

说我有以下模型:

class Race < ApplicationRecord
  has_many :horses
end

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

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

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

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

1 个答案:

答案 0 :(得分:0)

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] )
相关问题