5

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

4

1 に答える 1

6

リレーションに単純なエラーがあります。代わりに、次を使用して、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}})

との違いに注意してwidthくださいcomponents.0.width

これがあなたの道を歩むのに役立つことを願っています。

于 2012-05-15T15:14:33.833 に答える