I’m .clone -ing a record in rails…
new_blerg = Blerg.find(1).clone
This record has loads and loads of associations, and those associations even have associations.
Is there a way to deep-copy a record and clone it so it is cloned with all of those associations too?
You may get some good use out of the Amoeba gem for ActiveRecord 3.2.
It supports easy and automatic recursive duplication of
has_one,has_manyandhas_and_belongs_to_manyassociations, field preprocessing and a highly flexible and powerful configuration DSL that can be applied both to the model and on the fly.be sure to check out the Amoeba Documentation but usage is pretty easy…
just
or add
to your Gemfile
then add the amoeba block to your model and run the
dupmethod as usualYour new post should have all the tags that were originally associated with it, and all the comments should be duplicated as well. You can disable the duplication of various records through the DSL, which you can read about in the documentation, but for example, if you wanted to keep the tags, but not the comments you could do something like this:
or using the exclusive syntax
or by specifying which field types to recognize (and thusly copy)
each of these various options should result in re-associating the new post with the same tags as the old post, but without duplicating the comments.
Amoeba will also automatically recurse in to child records if you enable them
You can also prefix fields with some extra data to indicate uniqueness
and in addition to prepend you can also append to or run a regex on a given field
Enjoy! 🙂