Problem creating records through association using .new

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

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

Foreign keys are always filled in at save time.

Jason

@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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs