Awesome Nested Set is an implementation of the nested set pattern for ActiveRecord models. It is replacement for acts_as_nested_set and BetterNestedSet, but more awesome.
Version 2 supports Rails 3. Gem versions prior to 2.0 support Rails 2.
This is a new implementation of nested set based off of BetterNestedSet that fixes some bugs, removes tons of duplication, adds a few useful methods, and adds STI support.
Add to your Gemfile: gem 'awesome_nested_set'
To make use of awesome_nested_set, your model needs to have 3 fields: lft, rgt, and parent_id. You can also have an optional field: depth:
classCreateCategories<ActiveRecord::Migrationdefself.upcreate_table:categoriesdo|t|t.string:namet.integer:parent_idt.integer:lftt.integer:rgtt.integer:depth# this is optional.endenddefself.downdrop_table:categoriesendend
Enable the nested set functionality by declaring acts_as_nested_set on your model
classCategory<ActiveRecord::Baseacts_as_nested_setend
Run ‘rake rdoc` to generate the API docs and see CollectiveIdea::Acts::NestedSet for more info.
It’s generally best to “white list” the attributes that can be used in mass assignment:
classCategory<ActiveRecord::Baseacts_as_nested_setattr_accessible:name, :parent_idend
If for some reason that is not possible, you will probably want to protect the lft and rgt attributes:
classCategory<ActiveRecord::Baseacts_as_nested_setattr_protected:lft, :rgtend
Coming from acts_as_tree or another system where you only have a parent_id? No problem. Simply add the lft & rgt fields as above, and then run
Category.rebuild!
Your tree will be converted to a valid nested set. Awesome!
The view helper is called #nested_set_options.
Example usage:
<%= f.select :parent_id, nested_set_options(Category, @category) {|i| "#{'-' * i.level} #{i.name}" } %>
<%= select_tag 'parent_id', options_for_select(nested_set_options(Category) {|i| "#{'-' * i.level} #{i.name}" } ) %>See CollectiveIdea::Acts::NestedSet::Helper for more information about the helpers.
You can learn more about nested sets at: threebit.net/tutorials/nestedset/tutorial1.html
If you find what you might think is a bug:
Check the GitHub issue tracker to see if anyone else has had the same issue. github.com/collectiveidea/awesome_nested_set/issues/
If you don’t see anything, create an issue with information on how to reproduce it.
If you want to contribute an enhancement or a fix:
Fork the project on GitHub. github.com/collectiveidea/awesome_nested_set/
Make your changes with tests.
Commit the changes without making changes to the Rakefile, VERSION, or any other files that aren’t related to your enhancement or fix
Send a pull request.
Copyright ©2008 Collective Idea, released under the MIT license