forked from xavier/acts-as-tree-with-dotted-ids
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
72 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
acts_as_tree_with_dotted_ids | ||
============================ | ||
|
||
This is an extension to Rails good old acts_as_tree which uses an extra "dotted_ids" column | ||
which stores the path of the node as a string of ID joined by dots, hence the name. | ||
|
||
This optimization solves performance issues related to in-database tree structure by allowing | ||
for direct O(1) ancestor/child verification and O(N) subtree access with one single query. | ||
|
||
class Category < ActiveRecord::Base | ||
acts_as_tree_with_dotted_ids :order => "name" | ||
end | ||
|
||
Example: | ||
root | ||
\_ child1 | ||
\_ subchild1 | ||
\_ subchild2 | ||
|
||
root = Category.create("name" => "root") | ||
child1 = root.children.create("name" => "child1") | ||
subchild1 = child1.children.create("name" => "subchild1") | ||
|
||
root.parent # => nil | ||
child1.parent # => root | ||
root.children # => [child1] | ||
root.children.first.children.first # => subchild1 | ||
|
||
root.id # 1 | ||
root.dotted_ids # "1" | ||
child1.id # 2 | ||
child1.dotted_ids # "1.2" | ||
subchild1.id # 3 | ||
subchild1.dotted_ids # "1.2.3" | ||
|
||
|
||
The plugin adds the following instance methods: | ||
|
||
* ancestor_of?(node) | ||
* self_and_ancestors | ||
* descendant_of?(node) | ||
* all_children | ||
* depth | ||
|
||
The following methods of have been rewritten to take advantage of the dotted IDs: | ||
|
||
* root | ||
* ancestors | ||
* siblings | ||
* self_and_sibblings | ||
|
||
If you already have an acts_as_tree model, you can easily upgrade it to take advantage of the dotted IDs. | ||
|
||
1. Just add the "dotted_ids" column to your table. | ||
In most case a string should be enough but if your tree is very deep you may want to use a text column. | ||
|
||
2. Call MyTreeModel.rebuild_dotted_ids! and your ready to go. | ||
|
||
|
||
Compatibility | ||
|
||
Tested with Rails 2.x. | ||
Tested with MySQL 5.x and SQLite. | ||
|
||
|
||
Thanks | ||
|
||
Kudos to all the contributors to the original plugin. | ||
|
||
|
||
Copyright (c) 2007 David Heinemeier Hansson, released under the MIT license | ||
Copyright (c) 2008 Xavier Defrang, released under the MIT license |