Forum: Ruby on Rails Clone ActiveRecords

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Edwin M. (Guest)
on 2007-05-03 12:05
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


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., I am effectively updating the same database record as the

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 ?

Edwin M. (Guest)
on 2007-05-05 06:33
(Received via mailing list)
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>
This topic is locked and can not be replied to.