# Problem creating records through association using .new

**URL:** <https://www.ruby-forum.com/t/problem-creating-records-through-association-using-new/92732>\
**Category:** Rails\
**Created:** [April 23, 2007, 4:24pm UTC](https://www.ruby-forum.com/t/problem-creating-records-through-association-using-new/92732 "2007-04-23T16:24:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 23, 2007, 4:24pm UTC](https://www.ruby-forum.com/t/problem-creating-records-through-association-using-new/92732/1 "2007-04-23T16:24:18Z")

</div>

Hello,

When I do

order = Order.find :first  
line\_item = order.line\_items.new  
line\_item.save

the LineItem object is saved with order\_id = nil.

However, if I just do order.line\_item.create, order\_id is filled out  
correctly and it saves the association.

Why doesn’t it work with .new?

Thanks,

Andrew

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 23, 2007, 4:30pm UTC](https://www.ruby-forum.com/t/problem-creating-records-through-association-using-new/92732/2 "2007-04-23T16:30:54Z")

</div>

Well, because it doesn’t work that way. #create saves, #new doesn’t.

Foreign keys are always filled in at save time.

Jason

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 23, 2007, 4:36pm UTC](https://www.ruby-forum.com/t/problem-creating-records-through-association-using-new/92732/3 "2007-04-23T16:36:26Z")

</div>

@Jason: I think he means the Foreign key is nil (order\_id in the  
line\_item  
class should have been filled in for him because of the association.)

@Andrew:

Collection#new doesn’t work that way… in fact if you look at the API  
for  
has\_many you won’t even see a ‘new’ method.

You want ‘build’

order.line\_items.build (:thing =\> other\_thing… }

(I hate that syntax… new makes more sense there than build. )
