How do you create a copy / duplicate mongoid object?

ActiveRecord safely supports dup , but mongoid does not seem to handle it properly.

I would like to do the following:

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

And y must be a completely new object so that:

 x != y x.id != y.id 
+7
source share
1 answer

Try the following:

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

It should change _id and copy all other fields. I noticed that this does not seem to work with inline documents. For each embedded document in the original, it creates an empty subdocument in the clone with a new identifier, but does not fill out any of the other fields.

If you work with embedded documents, it is better to write your own class method.

+17
source

All Articles