The Decider said about 1 year ago permalink Comment? (0)
Tagged: rails nested set

Awesome Nested Set Revealed!

Ok, there’s nothing new with nested sets in rails but I crawled through the Awsome Nested Set Code from CollectiveIdea on GitHub code and made a quick and dirty cheat sheet. Here you go.

Awesome Nested Set Cheat Sheet:

Basic Usage

Create a root node:

my_root = Category.create! :name => ‘root’

Put a new thing inside this root node:

my_new_thing = Category.create! :name => ‘Chair’ my_new_thing.move_to_child_of my_root

Put a “new” new thing inside this “new_thing” node:

my_2nd_new_thing = Category.create! :name => ‘Chair’ my_2nd_new_thing.move_to_child_of my_new_thing

Now you should have something that resembles this:

+ root |_____ my_new_thing |_____________ my_2nd_new_thing

Gratuitous picture of my dog Ella.

ella goes for ball

Accessing the data:

Class methods:

  • Category.root – returns the first root node
  • Category.roots – returns all root nodes

Instance methods:

  • my_cat.root? – true if this is a root node
  • my_cat.leaf? – true if this is a leaf node. It has no children.
  • my_cat.leaves – returns array of all nodes without children.
  • my_cat.child? – true if this is a child node. It has a parent.
  • my_cat.root – root for this node.
  • my_cat.parent – returns the immediate parent
  • my_cat.self_and_ancestors – returns array of all parents and self
  • my_cat.ancestors – returns array of all parents. Not including self.
  • my_cat.self_and_siblings – returns array of brothers and sisters and self. All at that level.
  • my_cat.siblings – returns array of brothers and sisters. Not including self.
  • my_cat.level – returns the level of this object in the tree. root = 0
  • my_cat.self_and_descendants – returns array of all children and self
  • my_cat.descendants – returns array of all children. Not including self.
  • my_cat.children – returns array of immediate children. Just those in the next level.
  • my_cat.is_descendent_of?(obj) – returns true if self is nested under obj
  • my_cat.is_or_is_descendent_of?(obj) – returns true if self is nested under obj or self is obj
  • my_cat.is_ancestor_of?(obj) – returns true if nested by any obj
  • my_cat.is_or_is_ancestor_of?(obj) – returns true if nested by any obj or self is obj
  • Comments

    simple_captcha.jpg
    Are you a Human? Type the code above.