ActsAsTree extends ActiveRecord to add simple support for organizing items into parent–children relationships. By default, ActsAsTree expects a foreign key column called parent_id
.
class Category < ActiveRecord::Base
acts_as_tree order: "name"
end
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
We also have a convenient TreeView
module you can mixin if you want a little visual representation of the tree structure. Example:
class Category < ActiveRecord::Base
extend ActsAsTree::TreeView
acts_as_tree order: 'name'
end
> Category.tree_view(:name)
root
|_ child1
| |_ subchild1
| |_ subchild2
|_ child2
|_ subchild3
|_ subchild4
=> nil
And there's a TreeWalker
module (traversing the tree using depth-first search (default) or breadth-first search) as well. Example given the Model Page
as
class Page < ActiveRecord::Base
extend ActsAsTree::TreeWalker
acts_as_tree order: 'rank'
end
In your view you could traverse the tree using
<% Page.walk_tree do |page, level| %>
<%= link_to "#{'-'*level}#{page.name}", page_path(page) %><br />
<% end %>
You also could use walk_tree as an instance method such as:
<% Page.first.walk_tree do |page, level| %>
<%= link_to "#{'-'*level}#{page.name}", page_path(page) %><br />
<% end %>
We no longer support Ruby 1.8 or versions of Rails/ActiveRecord older than 3.0. If you're using a version of ActiveRecord older than 3.0 please use 0.1.1.
Moving forward we will do our best to support the latest versions of ActiveRecord and Ruby.
The Change Log has moved to the releases page.
rake release
This will create and push a tag to GitHub, then generate a gem and push it to
Rubygems.Copyright (c) 2007 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.