I just encountered a situation where adding “autosave: true” to an association changed the validation errors I get on creation of parent & child together - but it wasn’t obvious to me from any docs that “autosave: true” would change any behavior during creation.
This behavior caught me off-guard, but it appears to be intentional (https://github.com/rails/rails/blob/master/activerecord/lib/active_record/autosave_association.rb#L326). However, I haven’t seen an explanation or reasoning for it. My expectation was that adding “autosave: true” would only change behavior during update without affecting create behavior. Is this documented somewhere - other than the terse https://github.com/rails/rails/blob/master/activerecord/lib/active_record/autosave_association.rb#L13 “If validations for any of the associations fail, their error messages will be applied to the parent.”, which isn’t obvious to me that there will be different behavior for “autosave: true” vs. no autosave option specified.
Thanks for your thoughts,
Steve
Here’s a demo:
class Mother < ActiveRecord::Base
has_many :daughters
end
class Daughter < ActiveRecord::Base
belongs_to :mother
validates :name, presence: true
end
mom = Mother.new
mom.daughters.build()
mom.save
puts mom.errors.messages
#=> {:daughters=>[“is invalid”]}
class Father < ActiveRecord::Base
has_many :sons, autosave: true
end
class Son < ActiveRecord::Base
belongs_to :father
validates :name, presence: true
end
dad = Father.new
dad.sons.build()
dad.save
puts dad.errors.messages
#=> {:“sons.name”=>[“can’t be blank”]}