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

罗伯托

我无法使用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

谢谢你的帮助!

罗伯托

Mongoid迅速迫使我成为酒鬼。希望它可以帮助处于相同情况的人。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章