0

正しいネストされた埋め込みドキュメントを mongoid で保存するのに問題があります。v3.1.6 と v4.0.0 の両方でこれを試しましたが、結果は同じです。親ドキュメントは保存されますが、変更したネストされたドキュメントは変更を無視し、代わりに最初のネストされたドキュメントを更新します。

次のようないくつかのモデルを想定します。

Mongoid.configure do |config|
  config.sessions = {default: {hosts: ["localhost:27017"], database: "test_mongoid"}}
end

class Band
  include Mongoid::Document

  field :name, type: String
  embeds_many :members
end

class Member
  include Mongoid::Document
  embedded_in :band

  field :name, type: String
  embeds_many :instruments
end

class Instrument
  include Mongoid::Document
  embedded_in :member

  field :name, type: String

  def make_badass!
    self.name = "Badass #{self.name}"
    self.save
  end
end

そして実行するプログラム:

Band.destroy_all

a_band = {
  name: "The Beatles",
  members: [
    {
      name: 'Paul',
      instruments: [
        {
          name: 'Bass guitar'
        },
        {
          name: 'Voice'
        }
      ]
    }
  ]
}
Band.create(a_band)


the_beatles = Band.first

puts the_beatles.as_document

paul = the_beatles.members.first
voice = paul.instruments.where({name: "Voice"}).first

voice.make_badass!

puts Band.first.as_json

データベースには次が含まれているはずです。

{
    "_id": ObjectId('53aa7d966d6172889c000000'),
    "name" : "The Beatles",
    "members" : [
        {
            "_id" : ObjectId('53aa7d966d6172889c010000'),
            "name" : "Paul",
            "instruments" : [
                {"_id" : ObjectId('53aa7d966d6172889c020000'), "name" : "Bass guitar"},
                {"_id" : ObjectId('53aa7d966d6172889c030000'), "name" : "Voice"}
            ]
        }
    ]
}

ただし、代わりに次のものが含まれます。

{
    "_id": ObjectId('53aa7d966d6172889c000000'),
    "name" : "The Beatles",
    "members" : [
        {
            "_id" : ObjectId('53aa7d966d6172889c010000'),
            "name" : "Paul",
            "instruments" : [
                {"_id" : ObjectId('53aa7d966d6172889c020000'), "name" : "Badass Voice"},
                {"_id" : ObjectId('53aa7d966d6172889c030000'), "name" : "Voice"}
            ]
        }
    ]
}

のインスタンス メソッド内から正しい埋め込みドキュメントを変更する有効な方法はですかInstrument?

ご協力いただきありがとうございます!

4

1 に答える 1

0

モンゴイドはすぐに私をアルコール依存症にさせます。うまくいけば、同じ状況の誰かを助けるでしょう。

class Instrument
  include Mongoid::Document
  embedded_in :member

  field :name, type: String

  def make_badass
    self.name = "Badass #{self.name}"
    self.member.band.save
  end

  def unset_name
    # self.unset :name does not work
    self.remove_attribute :name
    self.member.band.save
  end

end
于 2014-06-25T08:10:26.597 に答える