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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With