Replying to yourself is the sign of a sad life, I know, but....
After another read of the pragmatic book and the docs, it looks like
the standard array methods aren''t all AR-aware (concat), so I ended up
doing something like this:
cart2.items.each { | item |
cart1.items << item
item.save
}
cart2.destroy
This, I think, should be ok - the copy updates the foreign key, and
the item is saved, and thus shouldn''t be deleted with cart2.
The other problem I have is that cart1 may potentially be a new
(unsaved) object, which I''m pretty sure is bad (assigning existing DB
objects to an unsaved parent object). In this case, I can''t save the
child object without saving the parent. I guess the solution is create
the parent, save it, then add and save the children...
On 7/12/05, Colin Fleming
<colin.mailinglist-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:> Is it ok to do this? My knowledge of the rails internals isn''t
good
> enough to work this out. Say I have a cart that has_many items. If I
> then have two carts, and I want to merge them, can I do this:
>
> cart1.items.concat(cart2.items)
> cart2.items.clear
> cart2.destroy
> cart1.save
>
> I think this should be ok, since assigning the object should reset the
> primary key, and the copied objects should be saved with cart1. What
> I''m not sure about is if the db state will get screwed up if I
have
> dependent => true on the has_many declaration - it looks like the
> destroy will then delete the objects from the db, and the update of
> the child objects will fail. I guess this might be better if I do
> cart1.save before cart2.destroy, because all the objects should then
> be associated with cart1.
>
> Or is there an easier way to do this?
>