当我尝试更新嵌入式文档(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上来简化事件,则会观察到相同的行为。
这是一个完全合理的问题 - 不知道为什么你得到低估。 – theTRON