Forum: Ruby on Rails When are activerecord associations made?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
241f31d880c3d2a0e59da07a401e5820?d=identicon&s=25 Christopher Lee (Guest)
on 2009-03-20 21:34
(Received via mailing list)
Hello,

My question is when ActiveRecord associations are actually made?  To
me, it doesn't seem like the relationship is made until of the objects
is saved into the database.  Let's say i have models like:

Library has_many :books
Book belongs_to :Library

If I have code such as:

book = Book.new

library = Library.new
library.books << book

it seems like library.books is empty UNTIL book is first saved.

this causes strange problems for me if I am trying to validate that a
book always belongs to a library, and a library has to have a least
one book.

Maybe I'm thinking about this the wrong way?

Thanks in advance,
Chris
661ae6e97d0e16c2af2aaf7d197e8387?d=identicon&s=25 Sijo k g (sijo)
on 2009-03-23 09:56
Write as

library = Library.new(params)
book = library.books.build(params)
library.save

Sijo
This topic is locked and can not be replied to.