Cloning a one-many association


#1

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


#2

Hi, Joerg,

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

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

Best regards
Jan