11

ActiveRecord safely supports dup, but mongoid doesn't appear to handle it properly.

I'd like to do the following:

x = MyModel.new
x.save
y = x.dup
y.save

And y should be a totally new object such that:

x != y
x.id != y.id
Community
  • 1
  • 1
Travis Reeder
  • 38,611
  • 12
  • 87
  • 87
  • Looks like someone already got this: http://stackoverflow.com/questions/8793647/deep-clone-document-with-embedded-associations – Daniel Jan 31 '14 at 04:18

1 Answers1

21

Try this:

x = Item.new
x.save
y = x.clone
y.save

It should change the _id and copy all the other fields. I've noticed this doesn't seem to work with embedded documents though. For each embedded doc in the original, it creates a blank embedded doc in the clone with a new id, but doesn't populate any of the other fields.

If working with embedded docs it might be better to write your own class method.

Vickash
  • 1,076
  • 8
  • 8