Is it possible to access the child from errors on the parent record of the active record?

Given the ratio expressed below:

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

Suppose we have a parent with several children, one or more of which have errors that cause parent.valid? to return false.

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

Is there a way to access the child that caused errors while viewing the parent.errors object?

+5
source share
3 answers

As John suggested in the comments, I ignored the mistakes the parents added for the children, and crossing the children and adding their errors manually. The problem was complicated by having a has_many pair: through relationships, but John's suggestion was what I used.

0

, . Parent

validates_associated :children

errors , . - ,

parent = Parent.new
parent.build_child
parent.valid?
parent.children.first.errors.messages
+1

Adding my solution as I hope this is useful:

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
0
source

All Articles