嵌入相同模型的两个不同模型

Two different models embedding the same model

我有两个非常相似的 collection。两者之间的唯一区别是一个 (Item1) 比另一个 (Item2) 有更多的细节。 collection 中的文档已经嵌入了 "Detail" 个文档:

项目 1:

{
    "_id" : ObjectId("5461c8f0426f727f16000000"),
    "n" : "Name 1",
    "detail" : {
        "d" : [ 
            "Frank Darabont"
        ],
        "a" : [ 
            "Tim Robbins", 
            "Morgan Freeman", 
            "Bob Gunton"
        ]
}

项目 2:

{
    "_id" : ObjectId("5461c8f0426f727f16000000"),
    "n" : "Name 1",
    "detail" : {
        "d" : [ 
            "Frank Darabont"
        ]
}

我想让两个文档中的 "detail" 字段相同。我在同一个应用程序中同时拥有模型 Item1 和 Item2,它们都嵌入了 "Detail"。我看到的解决方案是在两个模型中调用不同的 :detail 但这不起作用,因为它在 Item(1|2) 文档中查找不存在的子文档,返回 nil。我现在是这样的:

class Item1
  include Mongoid::Document

  embeds_one :detail1, :class_name => "Detail"

  field :n
end

class Item2
  include Mongoid::Document

  embeds_one :detail2, :class_name => "Detail"

  field :n
end

但是,为了检索 "detail" 子文档,我想要这样的东西:

class Item1
  include Mongoid::Document

  embeds_one :detail, as: :detail1, :class_name => "Detail"

  field :n
end

class Item2
  include Mongoid::Document

  embeds_one :detail, as: :detail2, :class_name => "Detail"

  field :n
end

这不符合我的预期。有没有办法实现我想要的或更改详细文档以在每个 collection 中具有不同的名称是唯一的解决方案? :

谢谢。

来自fine manual

Polymorphism

When a child embedded document can belong to more than one type of parent document, you can tell Mongoid to support this by adding the as option to the definition on the parents, and the polymorphic option on the child. On the child object, an additional field will be stored that indicates the type of the parent.

他们甚至包括一个示例(为清楚起见,省略了非嵌入部分):

class Band
  include Mongoid::Document
  embeds_many :photos, as: :photographic
end

class Photo
  include Mongoid::Document
  embedded_in :photographic, polymorphic: true
end

您应该可以这样设置:

class Item1
  include Mongoid::Document
  embeds_one :detail, as: :detailable
end
class Item2
  include Mongoid::Document
  embeds_one :detail, as: :detailable
end
class Detail
  include Mongoid::Document
  embedded_in :detailable, polymorphic: true
end