Skip to content

Awesome nested set cheat sheet

Ankit gupta edited this page Aug 6, 2013 · 12 revisions

Basic Usage

Create a root node:

science = Category.create!(:name => 'Science')

Put a new thing inside this root node:

physics = Category.create!(:name => 'Physics')
physics.move_to_child_of(science)

Put another thing inside the "physics" node:

gravity = Category.create!(:name => 'Gravity')
gravity.move_to_child_of(physics)

Reload the root node:

science.reload

Now you should have something that resembles this:

science
'-- physics
    '-- gravity

Advanced Usage

Accessing levels without a hit to the DB:

Category.each_with_level(Category.root.self_and_descendants) do |category, level|
  ...
end

Accessing Data

Class methods

Category.root   the first root node
Category.roots  all root nodes

Instance methods

my_cat.root                  root for this node
my_cat.level                 the level of this object in the tree (e.g. root = 0)
my_cat.parent                the node's immediate parent
my_cat.children              array of immediate children (just those in the next level)
my_cat.ancestors             array of all parents, parents' parents, etc, excluding self
my_cat.self_and_ancestors    array of all parents, parents' parents, etc, including self
my_cat.siblings              array of brothers and sisters (all at that level), excluding self
my_cat.self_and_siblings     array of brothers and sisters (all at that level), including self
my_cat.descendants           array of all children, children's children, etc., excluding self
my_cat.self_and_descendants  array of all children, children's children, etc., including self
my_cat.leaves                array of all descendants that have no children

Instance methods: Predicates (these don't need to hit the DB to respond)

my_cat.root?                         true if this is a root node
my_cat.child?                        true if this is a child node (i.e. it has a parent)
my_cat.is_ancestor_of?(obj)          true if nested by any obj
my_cat.is_or_is_ancestor_of?(obj)    true if nested by any obj or self is obj
my_cat.is_descendant_of?(obj)        true if self is nested under obj
my_cat.is_or_is_descendant_of?(obj)  true if self is nested under obj or self is obj
my_cat.leaf?                         true if this is a leaf node (i.e. it has no children)