# Clone ActiveRecords

**URL:** <https://www.ruby-forum.com/t/clone-activerecords/103179>\
**Category:** Rails\
**Created:** [May 2, 2007, 6:58pm UTC](https://www.ruby-forum.com/t/clone-activerecords/103179 "2007-05-02T18:58:52Z")\
**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 2, 2007, 6:58pm UTC](https://www.ruby-forum.com/t/clone-activerecords/103179/1 "2007-05-02T18:58:52Z")

</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 have many children:

In my model file I have:

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… thus if I were to save it (e.g.  
aClone.save), I am effectively writing it to the same database records

Question: what’s the best way to turn these cloned objects in the  
hierarchy into a new ActiveRecords that upon save are going to get  
created as a set of new records… AND that maintain has\_many  
relationships between them… is it just a matter of nil’ing out the  
id columns ?

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 2, 2007, 7:33pm UTC](https://www.ruby-forum.com/t/clone-activerecords/103179/2 "2007-05-02T19:33:56Z")

</div>

I guess setting the id column to nil is not cutting it… you also need  
to set the new\_record attribute on each cloned object to false ?
