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

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.
22cff534e3e25802bf451fd61f0d0e5d?d=identicon&s=25 andrewdmason@gmail.com (Guest)
on 2007-04-23 16:24
(Received via mailing list)
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
83ca41657a99b65d99889abe712ba5e2?d=identicon&s=25 Jason Roelofs (Guest)
on 2007-04-23 16: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.

Jason
6ef8cb7cd7cd58077f0b57e4fa49a969?d=identicon&s=25 Brian Hogan (Guest)
on 2007-04-23 16:36
(Received via mailing list)
@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. )
This topic is locked and can not be replied to.