Saving one-many associations (elegant solution please)


#1

What is the most elegant way to save new one-many associations?

order = Order.new(:name => “My Order”)
order.line_items << LineItem.new(:product_id => 1, :quantity => 2)
order.line_items << LineItem.new(:product_id => 2, :quantity => 5)
order.save

The above - which is by far the most elegant way of putting it - doesn’t
work for me - the line_items don’t get saved. Presumably because the
order does not have an id yet, so they’re not linked up.

What is the best way to deal with such one-many associations when
creating new ones, other than first saving the order, then adding the
line_items and saving the order again?

Thanks
Joerg


#2

On Sun, Jan 15, 2006 at 12:19:01PM +0100, Joerg D. wrote:

What is the best way to deal with such one-many associations when
creating new ones, other than first saving the order, then adding the
line_items and saving the order again?

You can use build.

order = Order.new(:name => ‘My Order’)
order.line_items.build(:product_id => 1, :quantity => 2)
order.line_items.build(:product_id => 2, :quantity => 5)
order.save

marcel


#3

Ah of course. I always misread the Agile Rails book for some reason.
Thanks.


#4

Marcel Molina Jr. wrote:

You can use build.

order = Order.new(:name => ‘My Order’)
order.line_items.build(:product_id => 1, :quantity => 2)
order.line_items.build(:product_id => 2, :quantity => 5)
order.save

What class/module is “build” in? Can’t find it anywhere in the rails
api…

b


#5

Ben M. wrote:

What class/module is “build” in? Can’t find it anywhere in the rails
api…

b

Look at the description of has_many in the api. It adds several methods
to your collection, ‘build’ is one of them. For some reason it doesn’t
show up by itself in the API.

_Kevin


#6

Kevin O. wrote:

Ben M. wrote:

What class/module is “build” in? Can’t find it anywhere in the rails
api…

b

Look at the description of has_many in the api. It adds several methods
to your collection, ‘build’ is one of them. For some reason it doesn’t
show up by itself in the API.

RDoc is limited to documenting the static structure of a program - i.e.
the code that is there in the source files. Rails uses a combination of
adding methods to application classes at runtime, and interpreting
method calls on the fly using method_missing. Features that are
implemented in this way have to be documented in the narrative text for
a class, and can’t appear in the RDoc-generated method index.

regards

Justin


#7

Is there a similar way to do this with HABTM relationships? I don’t
think build is included.