2011-03-09 14 views
5

文書が埋め込まれたmongomapper文書があり、それをコピーしたいと思います。本質的にはMongomapper:新しい文書に文書をコピーする

、私は何をしようとしていることは、このようなものです:

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

だから私は二つの異なるmongomapper文書で終わるしたいのですが、同じコンテンツを持ちます。

これはどのように行うべきですか?

+0

を、私は彼らを取得し、これを行うための唯一の方法は、親ドキュメント内に埋め込まれた文書をループで把握します属性を追加するには、ドキュメントのコピーがあるまで、これらの属性をそれぞれコピーして新しいドキュメントを作成します。誰か他の方法を考えることができますか? – futureshocked

答えて

4

これを達成するには、_idを変更する必要があります。同じ_idの文書は同じ文書であるとみなされ、別の_idの文書を保存すると新しい文書が作成されます。さておき、私は誰から派生人を追跡することができるように、私は新しいレコードで古い_idどこかに保存するために傾斜されるだろうが、それは必要ありません。同様に

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 

あなたは、単にこれを行うことができるはず

+0

ニースでは、新しいIDの作成と埋め込みドキュメントの処理方法を組み合わせることができます。つまり、ドキュメントと埋め込みドキュメントの新しいコピーに新しいIDを付けることができます。 – futureshocked

0

mongodb/mongomapperに既存のドキュメントのコピーを作成することはできないと思いますが、ドキュメント/埋め込みドキュメントとオリジナルのIDが衝突するようですおよびコピーされたドキュメント。

私は自分の問題を、ドキュメントの内容ではなく新しいドキュメントにコピーして解決しました。ここにサンプルがあります:

inspection = Inspection.find(params[:inspection_id]) #old document 
new_inspection = Inspection.create     #new target document 
items = inspection.items        #get the embedded documents from inspection 

items.each do |item|         #iterate through embedded documents 
    new_item = Item.create       #create a new embedded document in which 
                 # to copy the contents of the old embedded document 
    new_item.area_comment = item.area_comment   #Copy contents of old doc into new doc 
    new_item.area_name = item.area_name 
    new_item.area_status = item.area_status 
    new_item.clean = item.clean 
    new_item.save          #Save new document, it now has the data of the original 
    new_inspection.items << new_item     #Embed the new document into its parent 
    end 

new_inspection.save         #Save the new document, its data are a copy of the data in the original document 

これは実際に私のシナリオで非常にうまくいきました。しかし、人々が異なる解決策を持っているのであれば私は不思議です。

4

:私がやった少し読書から

duplicate_doc = doc.clone 
duplicate_doc.save 
関連する問題