# Clone ActiveRecords

**URL:** <https://www.ruby-forum.com/t/clone-activerecords/103243>\
**Category:** Rails\
**Created:** [May 3, 2007, 10:05am UTC](https://www.ruby-forum.com/t/clone-activerecords/103243 "2007-05-03T10:05:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![edmoss](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/bcef8e/32.png) [@edmoss](https://www.ruby-forum.com/u/edmoss)\
**Post date:** [May 3, 2007, 10:05am UTC](https://www.ruby-forum.com/t/clone-activerecords/103243/1 "2007-05-03T10:05:58Z")

</div>

I am using the Marshal module to create a deep clone of an  
ActiveRecord object hierarchy… i.e. an object that has\_many  
children, which at their turn may have many children, etc.

In model file of the root object I have the following method:

def deep\_clone()

```
aClone = Marshal::load(Marshal.dump(self))

return aClone

```

end

This works fine, the returned clone contains the same has\_many  
hierarchy as the original…

However, it also copies the value of the “id” attribute for each of  
the cloned objects in the hierarchy… if I were to save it (e.g.  
aClone.save), I am effectively updating the same database record as the  
original.

Question: what’s the best way to turn these cloned objects in the  
hierarchy into a new ActiveRecords such that upon save of the root  
object, the root and all it’s children in hierarchy get created as a set  
of new records and the children of the cloned object correctly point to  
their parents ?

Is it just a matter of setting the “@new\_record” attribute to “true” for  
each of the cloned objects in the hierarchy, after I called the clone  
method ?

Thanks,

---

<div class="post-metadata">

**Author:** ![edmoss](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/bcef8e/32.png) [@edmoss](https://www.ruby-forum.com/u/edmoss)\
**Post date:** [May 5, 2007, 4:33am UTC](https://www.ruby-forum.com/t/clone-activerecords/103243/2 "2007-05-05T04:33:12Z")

</div>

In the end I decided to write a custom routine to clone the hierarchy  
of ActiveRecords and play it safe; I believe the above approach will  
work, but since my hiearchy was only 3 levels deep and a few  
attributes at each level, I played it safe and hand coded it.

On May 3, 1:05 am, Edwin M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
