Hi ! I have these models: class Invoice < AR::Base has_many :lines, :class_name => 'InvoiceLine' end class InvoiceLine < AR::Base belongs_to :invoice end This fails at the console: $ ruby script\console Loading development environment. >> invoice = Invoice.new => #<Invoice:0x3a76060 ...> >> line = invoice.lines.build => #<InvoiceItem:0x3a5d610 ...> >> invoice.save! ActiveRecord::RecordInvalid: Validation failed: Lines is invalid from ./script/../config/../config/../vendor/rails/activerecord/lib/active_record/validations.rb:736:in `save!' from (irb):3 >> puts line.errors.full_messages Invoice can't be blank I was under the impression that saving the parent should correctly save the children in has_many relationships. Of course, if I save the parent before the child, it works. But then I lose #new_record? Of course, AR::Base has an attribute named @new_record_before_save, but there are no accessors for it. http://dev.rubyonrails.org/browser/trunk/activerecord/lib/active_record/associations.rb#L93 seems to imply that the use case above will work, while http://dev.rubyonrails.org/browser/trunk/activerecord/lib/active_record/associations.rb#L279 says it won't work if "this object" is nil. "this object" is obviously not nil, but it hasn't received it's primary key yet. Question #1: Should saving the parent record correctly save the child record ? Question #2: Should we provide an accessor for @new_record_before_save Thanks !
on 06.03.2006 18:06
on 08.03.2006 23:01
I've also come up to this oddity and I'd like to know the answer to the questions pose--is the author of the original code present, or an otherwise knowledgeable person who could answer? Duane Johnson (canadaduane)
on 09.03.2006 02:40
2006/3/8, Duane Johnson <duane.johnson@gmail.com>: > I've also come up to this oddity and I'd like to know the answer to > the questions pose--is the author of the original code present, or an > otherwise knowledgeable person who could answer? Ok, I found the solution: http://blog.teksol.info/articles/2006/03/08/do-not-validate-belongs_to-or-else Summary: class Child < AR::Base validates_presence_of :parent_id end NOT class Child < AR::Base validates_presence_of :parent end Bye !
on 09.03.2006 02:49
2006/3/8, Francois Beausoleil <francois.beausoleil@gmail.com>: > class Child < AR::Base > validates_presence_of :parent_id > end http://dev.rubyonrails.org/ticket/4147