Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a copy / dup a mongoid object?

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
like image 464
Travis Reeder Avatar asked Aug 20 '12 19:08

Travis Reeder


1 Answers

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.

like image 198
Vickash Avatar answered Oct 04 '22 13:10

Vickash