【问题标题】:How to embed a Mongoid tree in another document?如何在另一个文档中嵌入 Mongoid 树?
【发布时间】:2011-01-11 22:24:50
【问题描述】:

我正在使用mongoid-tree,但这个问题可能适用于其他acts_as_tree ports for Mongoid

我想要一棵节点树,并且我想要将整个树嵌入到另一个文档中。我的问题是,这实际上只需要嵌入根节点,但所有节点都具有相同的embedded_in。就我而言:

class Container
  include Mongoid::Document

  embeds_one :root, :class_name => "Node"
end

class Node
  include Mongoid::Document
  include Mongoid::Tree

  embedded_in :container, :inverse_of => :root
end

我该如何设置,以便每棵树只有一条记录嵌入到容器中?还有其他更好的方法吗?

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    mongoid-tree 的作者benedikt,在 GitHub 上回答。

    目前 Mongoid::Tree 不适用于嵌入式节点。他建议:

    class Container
      include Mongoid::Document
    
      referenced_in :node, :inverse_of => :container
    end
    
    class Node
      include Mongoid::Document
      include Mongoid::Tree
    
      references_one :container
    end
    

    通过这种方式,您可以将任何节点分配给容器。您还可以覆盖 Node.container 方法来为子节点调用 root.container,这样您也可以获得子节点的容器。

    【讨论】:

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