Forum: Ruby on Rails Cloning a one-many association

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.
34791e1d8c4def65f9b93294638a7e04?d=identicon&s=25 Joerg Diekmann (joergd)
on 2006-01-15 15:40
Hi, I want to make a copy of an object with its associations, and I am
looking for an elegant solution. This is what I intuitively think should
work, but it doesn't:

order2 = order1.clone
order1.line_items.each do |o|
  order2.line_items.build(o)
end

This doesn't work because a model class does not stringify its keys ...
so I can't pass an object into a method that wants a hash, because an
object doesn't convert itself to a hash when needed.

Is there a simple way to solve this problem, or is this something where
I will need to do my own plumbing of sorts?

Thanks
Joerg
E48d29dc8fedb2878fa518d41cc63d88?d=identicon&s=25 Jan Prill (Guest)
on 2006-01-15 18:19
(Received via mailing list)
Hi, Joerg,

haven't tried it myself, but you might want to try:

order2.line_items.build(o.attributes())

Best regards
Jan
This topic is locked and can not be replied to.