Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongomapper: copy a document into a new document

Tags:

mongomapper

I have a mongomapper document with embedded documents, and want to make a copy of it.

In essence, what I am trying to do is something like this:

customer = Customer.find(params[:id])
new_customer = Customer.new
new_customer = customer
new_customer.save

So I want to end up with two different mongomapper documents, but with identical content.

Any ideas how this should be done?

like image 285
futureshocked Avatar asked Mar 09 '11 06:03

futureshocked


1 Answers

To accomplish this, you need to change the _id. Documents with the same _id are assumed to be the same document so saving a document with a different _id will create a new document.

customer = Customer.find(params[:id])
customer._id = BSON::ObjectId.new # Change _id to make a new record
  # NOTE: customer will now persist as a new document like the new_document 
  # described in the question.
customer.save # Save the new object

As an aside, I would be inclined to store the old _id somewhere in the new record so I could keep track of who derived from who, but it is not necessary.

like image 180
John F. Miller Avatar answered Dec 28 '22 00:12

John F. Miller