【问题标题】:How to tell which of the associated models fails my ActiveRecord validation?如何判断哪些关联模型未通过我的 ActiveRecord 验证?
【发布时间】:2023-03-04 18:40:01
【问题描述】:

假设我有以下模型:

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 甚至一个索引就足够了。

【问题讨论】:

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


    【解决方案1】:
    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] )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-22
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多