Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access a child object from the errors on an active record parent?

Given the relationship 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

Let's assume we have a parent object with multiple 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 element that caused the errors when looking at the parent.errors object?

like image 539
biagidp Avatar asked Nov 13 '22 22:11

biagidp


1 Answers

Yes, you could do it. Add to your Parent model

validates_associated :children

After that you can call errors method on every parent's child to find validation errors. Something like this to see child error messages

parent = Parent.new
parent.build_child
parent.valid?
parent.children.first.errors.messages
like image 100
Nick Kugaevsky Avatar answered Dec 25 '22 16:12

Nick Kugaevsky