Skip to content

normelton/amazing_nested_set

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AmazingNestedSet

Amazing Nested Set is an improved implementation of the nested set pattern.

See dev.mysql.com/tech-resources/articles/hierarchical-data.html for more information about storing hierarchical data in a relational database.

Why another nested-set implementation?

There are a number of very good nested set implementations already available. Underneath the covers, this implementation functions very differently from others:

  • Once a node is loaded, a “snapshot” of the entire tree is stored in memory. Subsequent operations are handled in the snapshot.

  • In addition, the left and right positions of each node are stored as floats, rather than the typical integer.

Key Features

  • Nodes can be inserted into the tree before saving. In fact, an entire tree can be built without a single database call. This allows a node to use the standard Rails validation framework to verify its position within the tree. If the validation fails, the node will not be saved into the tree.

  • Adding or repositioning a node does not alter other nodes in the database, since left and right position indices are not necessarily sequential integers.

  • Full support for single-table inheritance.

  • Nodes can be automatically sorted upon insertion.

  • No need for a parent_id column.

Usage

To make use of amazing_nested_set, add two fields to your model: lft and rgt:

class CreateCategories < ActiveRecord::Migration
  def self.up
    create_table :categories do |t|
      t.integer :set_id
      t.float :lft
      t.float :rgt
      t.string  :name
    end
  end

  def self.down
    drop_table :categories
  end
end

To add the capabilities to your model:

class Category < ActiveRecord::Base
  acts_as_nested_set
end

If the node class implements the Comparable mixin, an optional autosort attribute may be passed specifying that nodes are to be inserted in order. Refer to the API docs for more information.

Run rake rdoc to generate the API docs and see NormElton::Acts::NestedSet::SingletonMethods for more info.

Warning

This code may misbehave if two instances of the same tree are being modified simultaneously.

Inspirations

Other implementations of hierarchical data include:

Copyright © 2008 Norman Elton, released under the MIT License

About

An improved nested-set plugin for Rails

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages