2012-05-14 48 views
4

當我嘗試更新嵌入式文檔(embeds_many)上的屬性時,mongoid無法保存更改,並且好奇地將更改後的屬性添加爲父文檔上的新屬性。下面是一個簡單的單元測試,說明我想做的事:使用Mongoid更新嵌入式文檔而不是更新父文檔

class Tab 
    include Mongoid::Document 
    field :name, :type => String 
    embeds_many :components, :class_name => 'TabComponent' 
end 

class TabComponent 
    include Mongoid::Document 
    embeds_many :components, :class_name => "TabComponent" 
end 

class TabColumn < TabComponent 
    field :width, :type => Integer 
end 

require 'test_helper' 

class TabTest < ActiveSupport::TestCase 
    test "create new tab" do 
    tab = Tab.new({ 
     :name => "My Demo Tab", 
     :components => [TabColumn.new({ 
     :width => 200 
     })] 
    }) 

    tab.save! 

    tab.components[0].width = 300 
    tab.save! 

    assert_equal tab.components[0].width, 300 # passes 
    tab.reload 
    assert_equal tab.components[0].width, 300 # fails! 
    end 
end 

這裏是日誌輸出:

MONGODB (39ms) beam_test['system.namespaces'].find({}) 
MONGODB (27ms) beam_test['$cmd'].find({"count"=>"tabs", "query"=>{}, "fields"=>nil}).limit(-1) 
MONGODB (38ms) beam_test['tabs'].find({}) 
MONGODB (0ms) beam_test['tabs'].remove({:_id=>BSON::ObjectId('4fb153c4c7597fbdac000002')}) 
MONGODB (0ms) beam_test['tabs'].insert([{"_id"=>BSON::ObjectId('4fb15404c7597fccb4000002'), "name"=>"My Demo Tab", "components"=>[{"_id"=>BSON::ObjectId('4fb15404c7597fccb4000001'), "_type"=>"TabColumn", "width"=>200}]}]) 
MONGODB (0ms) beam_test['tabs'].update({"_id"=>BSON::ObjectId('4fb15404c7597fccb4000002')}, {"$set"=>{"width"=>300}}) 
MONGODB (27ms) beam_test['tabs'].find({:_id=>BSON::ObjectId('4fb15404c7597fccb4000002')}).limit(-1) 

難道我做錯了什麼?請注意,我認爲問題不是多態,如果我通過將寬度放在TabComponent上來簡化事件,則會觀察到相同的行爲。

+0

這是一個完全合理的問題 - 不知道爲什麼你得到低估。 – theTRON

回答

5

您的關係中有一個簡單的錯誤,而是使用以下內容來完成embeds_many/embedded-in關係的對稱性。

class TabComponent 
    include Mongoid::Document 
    embedded_in :tab 
end 

在你的日誌輸出上面,你會看到:

MONGODB (0ms) beam_test['tabs'].update({"_id"=>BSON::ObjectId('4fb15404c7597fccb4000002')}, {"$set"=>{"width"=>300}}) 

上面的修復程序後,我現在得到:

MONGODB (0ms) free11819_mongoid_embedded_update_test['tabs'].update({"_id"=>BSON::ObjectId('4fb270fee4d30bbc20000002')}, {"$set"=>{"components.0.width"=>300}}) 

注意區別widthcomponents.0.width

希望這有助於讓你在路上。

+1

謝謝!這完全解決了我的問題。我從來沒有想到,我必須用這兩種方式來定義關聯。 – mockaroodev

+0

你也救了我的一天! :D – Bornfree

+0

非常感謝。不知何故錯過了我的一個模型:( – JVK