How do I perform validations checks (and insert error messages into an errors structure) on an attribute which is has_one association.
If an error has occured in “shirt” or “pants”, how can i access that error?
Will the error be in person.shirt.errors[:color] ?
When i trigger person.save, are validations for person.shirt activated?
When i trigger person.save and there is an error in person.shirt, where will the error message be saved? In person.shirt.errors or in person.errors?
class Person < ActiveRecord::Base
has_one : shirt
has_many : pants
validates :name, :presence => true
validates_length_of :name, :minimum => 3
end
person = Person.new(:name => "JD")
person.shirt.create(:color=> "red")
person.pants.create(:type=> "jeans")
person.valid?
You can validate an association of the model with
That way when you call
person.saveit will trigger the validations ofshirt.And yes, you can access the association’s error with
person.shirt.errorsbut be sure to do that after triggering validations. For example:This is because validations haven’t been ran yet. So you need to call either
saveorvalid?or any other method that triggers validations.And it’s the same for the associations:
but since you’re validating the associations with
validates_associatedit will be enough withperson.valid?to trigger shirt’s validations.