Forum: Ruby on Rails Problem creating records through association using .new

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
on 2007-04-23 18:24
(Received via mailing list)

When I do

order = Order.find :first
line_item =

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?


Jason R. (Guest)
on 2007-04-23 18:30
(Received via mailing list)
Well, because it doesn't work that way. #create saves, #new doesn't.

Foreign keys are always filled in at save time.

Brian H. (Guest)
on 2007-04-23 18:36
(Received via mailing list)
@Jason: I think he means the Foreign key is nil (order_id in the
class should have been filled in for him because of the association.)


Collection#new doesn't work that way... in fact if you look at the API
has_many you won't even see a 'new' method.

You want 'build' (:thing => other_thing.... }

(I hate that syntax... new makes more sense there than build. )
This topic is locked and can not be replied to.