Both records must have an id in order to create the has_many

Hi there,

my problem is to add an object to another object through
the->through-statement.

product = Product.new
product.save
p = Product.find(1)
catalogue = Catalogue.new
calatogue.products

=> []

catalogue.products << p

=> ActiveRecord::HasManyThroughCantAssociateNewRecords: Cannot
associate
new records through 'Catalogue#catalogue_items' on '#'. Both records
must have an id in order to create the has_many :through record
associating them.
       from

It's exactly was it says. You need to save catalogue first.

Fred

Frederick Cheung wrote:

Hi there,

=> ActiveRecord::HasManyThroughCantAssociateNewRecords: Cannot
associate
new records through 'Catalogue#catalogue_items' on '#'. Both records
must have an id in order to create the has_many :through record
associating them.
       from

It's exactly was it says. You need to save catalogue first.

I know, but what I don´t understand is:

in the console I do know:

product = Product.new
product.save
arr = Array.new
arr << product
catalogue = Catalogue.new(:products => arr)
calatogue.products

=> [#<Product id: 1, created_at: "2008-04-28 20:53:34", updated_at:
"2008-04-28 20:53:34">]

now i think without saving catalogue first, I have my first product in
my catalogue-product-list
but:

catalogue.save
p catalogue

=> #<Catalogue id: 1, created_at: "2008-04-28 20:55:10", updated_at:
"2008-04-28 20:55:10">

catalogue2 = Catalogue.find_by_id(2)
p catalogue2.products

=> []

shit.... And I don´t know realy why :frowning:

what should I do?!? take catalogue and create a knew empty catalogue2,
save this and copy all attributes of catalogue into catalogue2 and save
after that catalogue2 again?!?
uff.... that´s heavy :frowning:

> arr << product
> catalogue = Catalogue.new(:products => arr)

This doesn't work. you can only specify attributes in the options to
new/create.

what should I do?!? take catalogue and create a knew empty catalogue2,
save this and copy all attributes of catalogue into catalogue2 and save
after that catalogue2 again?!?

Edge rails (soon to be 2.1) doesn't have this restriction, you could
always do that. If not you sill just have to save catalogue2 first
before adding to catalogue2.products

Fred

That may not actually be true in general.. Definitely true for
has_many through though, since in 2.0 that association type has no =
method

Fred