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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With