Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: Can I copy associations?

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

like image 254
Paul Avatar asked Mar 27 '09 16:03

Paul


1 Answers

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 }
like image 164
MarkusQ Avatar answered Sep 22 '22 13:09

MarkusQ