Mongoid嵌套嵌入式文档保存忽略查询

时间:2014-06-25 07:55:44

标签: ruby mongoid mongoid3 mongoid4

我在使用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的实例方法中更改正确的嵌入式文档的工作方法是什么?

感谢您的帮助!

1 个答案:

答案 0 :(得分: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