When are activerecord associations made?


#1

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


#2

Write as

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

Sijo