埋め込みドキュメント(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に幅を設定して単純化すると、同じ動作が観察されます。