当我尝试更新嵌入文档 (embeds_many) 上的属性时,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 上放置宽度来简化事情,则会观察到相同的行为。