Module: Adocca

Defined in:
lib/acts_as_fast_nested_set.rb

Overview

Defines an act that behaves a bit like nested_set or tree, but is hopefully much faster.

Like the nested_set it is much faster than tree when selecting subtrees, but unlike nested_set it wont have to rewrite the entire tree for each insertion or deletion.

Each node is connected to a parent, and each node has a node_id.

The node_id is created by concatenating a new identifier to the parents node_id, or just creating a brand new identifier if no parent is present, and appending a dot.

An identifier is alphabetical, and the newest identifier is always alphabetically greater than the identifiers of its siblings.

An example list of valid node_ids: AAAA. <- a top level node, with only one trailing dot AAAA.AAAA. <- a child of the node above AAAA.AAAB. <- sibling nr one AAAA.AAAB.AAAA. <- a child of sibling nr one AAAA.AAAC. <- sibling nr two AAAB. <- top level node two AAAC. <- top level node three AAAC.AAAA. <- child of top level node three AAAD. <- top level node four

This structure makes it easy to find all children of a node: SELECT * FROM table WHERE node_id LIKE ‘AAAA.%’ <- selects top level node one and all its children SELECT * FROM table WHERE node_id LIKE ‘AAAA.AAAB.%’ <- selects sibling nr two and all its children

Deleting is naturally equally easy.

The tricky bit is generating node_ids - for that we use the counter_string, which increments like: “aaaa”.next == “aaab” “ZZZZ”.next == “ZZZa” “zzzz”.next == “zzzzAAAA”

This keeps the relation between node_ids within the tree intact, as well as provides a big (140000 entries) namespace for each level of the tree using only 5 chars in the node_id column, and providing an even bigger (basically unlimited) namespace with more than 5 chars in the node_id column (it will provide 140000 more entries for each extra 4 chars after the first 5)

If you want to have several trees with different sets of node_ids (for example, several comment-trees connected to different models in the system), you can add :uniqueness_scope as a param to the acts_as_fast_nested_set method.

Example: acts_as_fast_nested_set :uniqueness_scope => [:forum_id, :forum_class] <- Will have a separate tree of node_ids

for each unique combination of forum_id 
and forum_class in the model.

Defined Under Namespace

Modules: Acts