views:

332

answers:

2

Is there a way to copy the associations of one model to another...

template_model = MyModel.find(id)
new_model = template_model.clone
new_model.children << template_model.children # I want to *copy* children

...such that I copy the children from the template to the new model? (In fact this code moves children from the template to the new model).

I know I can do it manually be looping, but is there are more succinct way?

Thanks

+4  A: 

The problem is that you are cloning the template, but not cloning it's children. Try something like:

template_model = MyModel.find(id)
new_model = template_model.clone
new_model.children << template_model.children.collect { |child| child.clone }
MarkusQ
Perfect! That's it - nice and succinct. Thanks so much.
Paul
A: 

Well, it's not really a copy.

But you could do

new_model.child_ids = template_model.child_ids
Jimmy Stenke