# When are activerecord associations made?

**URL:** <https://www.ruby-forum.com/t/when-are-activerecord-associations-made/163488>\
**Category:** Rails\
**Created:** [March 20, 2009, 9:34pm UTC](https://www.ruby-forum.com/t/when-are-activerecord-associations-made/163488 "2009-03-20T21:34:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Christopher\_Lee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/3d9bf3/32.png) [@Christopher\_Lee](https://www.ruby-forum.com/u/Christopher_Lee)\
**Post date:** [March 20, 2009, 9:34pm UTC](https://www.ruby-forum.com/t/when-are-activerecord-associations-made/163488/1 "2009-03-20T21:34:02Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Christopher\_Lee](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/3d9bf3/32.png) [@Christopher\_Lee](https://www.ruby-forum.com/u/Christopher_Lee)\
**Post date:** [March 23, 2009, 9:56am UTC](https://www.ruby-forum.com/t/when-are-activerecord-associations-made/163488/2 "2009-03-23T09:56:48Z")

</div>

Write as

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

Sijo
