5

鉴于以下表示的关系:

class Parent < ActiveRecord::Base
  has_many :children, :dependent => :destroy

  accepts_nested_attributes_for :child
end

class Child < ActiveRecord::Base
  belongs_to :parent

  validates :name, :presence => true
end

假设我们有一个包含多个子对象的父对象,其中一个或多个子对象有导致 parent.valid 的错误?返回假。

parent = Parent.new
parent.build_child(:name => "steve")
parent.build_child()
parent.valid?

有没有办法在查看 parent.errors 对象时访问导致错误的子元素?

4

3 回答 3

1

是的,你可以做到。添加到您的Parent模型

validates_associated :children

之后,您可以errors在每个父母的孩子上调用方法来查找验证错误。像这样查看子错误消息

parent = Parent.new
parent.build_child
parent.valid?
parent.children.first.errors.messages
于 2012-09-17T17:18:06.253 回答
0

正如约翰在评论中所建议的那样,我最终忽略了为孩子添加到父级的错误并遍历孩子并手动添加他们的错误。有几个 has_many :through 关系使问题变得复杂,但约翰的建议是我最终使用的精髓。

于 2012-10-29T14:21:10.243 回答
0

添加我的解决方案,希望对您有所帮助:

class Parent < AR
  has_many :children, inverse_of: :parent
  validates_associated :children, message: proc { |_p, meta| children_message(meta) }

  def self.children_message(meta)
    meta[:value][0].errors.full_messages[0]
  end
  private_class_method :children_message
end

class Child < AR
  belongs_to :parent, inverse_of: :children
  validates :name, presence: true
end
于 2017-04-10T14:45:48.313 回答