How to embed a Mongoid tree in another document?
I'm using mongoid-tree but this question probably applies to other acts_as_tree ports for Mongoid.
I want a tree of nodes and I want the whole tree to be embedded in another document. My problem is that this really only requires that 开发者_C百科the root node be embedded but all nodes have the same embedded_in. In my case:
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
How can I set this up so that only one record per tree is embedded_in the Container? Is there another approach that would be better?
The author of mongoid-tree, benedikt, answered on GitHub.
Currently Mongoid::Tree doesn't work with embedded Nodes. He suggests:
class Container
include Mongoid::Document
referenced_in :node, :inverse_of => :container
end
class Node
include Mongoid::Document
include Mongoid::Tree
references_one :container
end
This way you any node can be assigned to a container. You could also overwrite the Node.container method to call root.container for child nodes so you'd get the container for subnodes as well.
精彩评论