【问题标题】:MongoId Embedded Document With Reference带有参考的 MongoId 嵌入式文档
【发布时间】:2015-02-18 03:21:11
【问题描述】:

我有以下情况,我有一个文档需要嵌入到某些文档中,但为了可追溯性(例如,需要知道订阅每种类型的人数)我需要将其存储为不同的文档。因此,当我尝试保存一组默认类型时,它会说:

Mongoid::Errors::NoParent: Problem: Cannot persist embedded document Type without a parent document.

我不知道该怎么做或如何处理这种情况,感谢任何帮助或建议。

class Type
  include Mongoid::Document
    embedded_in :typeable, polymorphic: true
    belongs_to :client
    field :count, type: Integer # number of people interested in each Type
end

class Client
  include Mongoid::Document
    has_many :types
    embeds_many :discounts, as: :discountable
end

class Discount
  include Mongoid::Document
    embeds_many :types, as: :typeable
    embedded_in :discountable, polymorphic: true
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 mongoid mongoid3


    【解决方案1】:

    简单的答案是您无法为嵌入式模型创建独立文档(您在架构上通过选择嵌入来防止这种情况发生)。如果您需要一组独立的类型,您应该使用has_manybelongs_to 而不是embeds_manyembedded_in

    【讨论】:

      【解决方案2】:

      你考虑过继承吗?

      让您的 ClientDiscount 模型继承自 Type
      他们将受益于您的 Type 字段,您也将能够拥有独立的 Type 索引。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-23
        相关资源
        最近更新 更多