2011-03-09 71 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的文檔將創建新文檔。

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 

順便說一句,我會傾向於在一些地方保存舊_id在新的記錄,所以我可以跟蹤誰從誰得到的,但它是沒有必要的。

+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 
相關問題