【问题标题】:Referencing Mongoid recursively_embeds_many from another Document从另一个文档中引用 Mongoid recursively_embeds_many
【发布时间】:2011-09-11 17:46:55
【问题描述】:

我有两个证明有问题的文档模型:

class Component
  include Mongoid::Document
  include Mongoid::Versioning

  recursively_embeds_many
end

class Institution
  include Mongoid::Document

  has_many :components
end

我了解您不应该能够从其他文档中引用嵌入式模型。但是,我希望使用递归嵌入的文档有一种方法可以从另一个文档中引用树的顶部?如果这根本不可能一起使用这些关系,我必须在机构和组件之间建立一对多关系,同时保持组件的递归性质?

【问题讨论】:

    标签: ruby-on-rails ruby mongoid


    【解决方案1】:

    您尝试做的事情听起来很合理,但 Mongoid 不会让您将可以通过关联嵌入到另一个类的类关联起来。当我试一试时,在向机构添加(顶级)组件时,this file(第 218 行)出现异常。

    对您来说最简单的选择是在机构中嵌入组件,例如

    class Institution
      include Mongoid::Document
    
      embeds_many :components
    end
    

    否则,如果您想与不同的机构共享组件树,我想您需要在模型中引入某种容器对象并定义与机构的多对多关联,例如:

    class Component
      include Mongoid::Document
      include Mongoid::Versioning
    
      recursively_embeds_many
    end
    
    class ComponentTree
      include Mongoid::Document
    
      embeds_many :components
      has_and_belongs_to_many :institutions
    end
    
    class Institution
      include Mongoid::Document
    
      has_and_belongs_to_many :component_trees
    end
    

    【讨论】:

    • 这基本上就是我所做的。并不是说概念上的组件不属于机构中的嵌入,而是每个机构都会有很多组件,并且它们会嵌套得很深,甚至不想考虑文档大小限制。
    • 啊,是的,文档大小限制通常似乎是嵌入文档中的一个因素。尽管最近对文档大小的限制从 4MB 增加到了 16MB,但从性能的角度来看,实际限制可能要低得多。
    猜你喜欢
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    相关资源
    最近更新 更多