Ordering

Mongoid::Tree doesn't order children by default. To enable ordering of
tree nodes include the Mongoid::Tree::Ordering module. This will add a
position field to your document and provide additional utility
methods:

class Node
include Mongoid::Document
include Mongoid::Tree
include Mongoid::Tree::Ordering
end

See Mongoid::Tree::Ordering for more information on these methods.

Traversal

It's possible to traverse the tree using different traversal methods
using the Mongoid::Tree::Traversal module.

Example:

class Node
include Mongoid::Document
include Mongoid::Tree
include Mongoid::Tree::Traversal
end
node.traverse(:breadth_first) do |n|
# Do something with Node n
end

Destroying

Mongoid::Tree does not handle destroying of nodes by default. However it
provides several strategies that help you to deal with children of deleted
documents. You can simply add them as before_destroy callbacks.

Available strategies are:

:nullify_children – Sets the children's parent_id to null

:move_children_to_parent – Moves the children to the current document's
parent

:destroy_children – Destroys all children by calling their #destroy method
(invokes callbacks)

class Node
include Mongoid::Document
include Mongoid::Tree
before_destroy :nullify_children
end

Callbacks

There are two callbacks that are called before and after the rearranging
process. This enables you to do additional computations after the documents
position in the tree is updated. See Mongoid::Tree for details.

Example:

class Page
include Mongoid::Document
include Mongoid::Tree
after_rearrange :rebuild_path
field :slug
field :path
private
def rebuild_path
self.path = self.ancestors_and_self.collect(&:slug).join('/')
end
end

Validations

Mongoid::Tree currently does not validate the document's children or
parent associations by default. To explicitly enable validation for
children and parent documents it's required to add a
validates_associated validation.

Example

class Node
include Mongoid::Document
include Mongoid::Tree
validates_associated :parent, :children
end

Build Status

mongoid-tree is on Travis running the
specs on Ruby 1.8.7, Ruby 1.9.2 and Ruby Enterprise Edition.