A Nested Set is similar to a tree from ActsAsTree. However the nested set allows building of the entire hierarchy at once instead of querying each nodes children, and their children. When destroying an object, a before_destroy trigger prunes the rest of the branch of object under the current object.
Table Schema
create table nested_objects (
id int(11) unsigned not null auto_increment,
parent_id int(11),
lft int(11),
rgt int(11),
name varchar(32),
primary key (id)
);
Code
class TreeItem < ActiveRecord::Base
acts_as_nested_set
end
Methods introduced by this feature are:
API documentation
Class methods
Instance methods
Alternatives
BetterNestedSet is an updated version with some additional features, available as a plugin.
Future
DHH has said that acts_as_nested_set will be relegated to a plugin in RoR 1.3.
Question: Can a scope be provided, such that multiple trees can exist within the same database table? Importantly, this could dramatically reduce the number of rows modified upon node insertion (i.e. only those having the same scope value). If so, how is this done? I haven’t found any documentation to demonstrate this.
Answer: with BetterNestedSet or acts_as_threaded this is possible and runs properly. Rails 1.2 also seems to add a scope argument to acts_as_nested_set.
To add acts_as_list methods see http://www.vaporbase.com/postings/List_methods_for_nested_sets
A Nested Set is similar to a tree from ActsAsTree. However the nested set allows building of the entire hierarchy at once instead of querying each nodes children, and their children. When destroying an object, a before_destroy trigger prunes the rest of the branch of object under the current object.
Table Schema
create table nested_objects (
id int(11) unsigned not null auto_increment,
parent_id int(11),
lft int(11),
rgt int(11),
name varchar(32),
primary key (id)
);
Code
class TreeItem < ActiveRecord::Base
acts_as_nested_set
end
Methods introduced by this feature are:
API documentation
Class methods
Instance methods
Alternatives
BetterNestedSet is an updated version with some additional features, available as a plugin.
Future
DHH has said that acts_as_nested_set will be relegated to a plugin in RoR 1.3.
Question: Can a scope be provided, such that multiple trees can exist within the same database table? Importantly, this could dramatically reduce the number of rows modified upon node insertion (i.e. only those having the same scope value). If so, how is this done? I haven’t found any documentation to demonstrate this.
Answer: with BetterNestedSet or acts_as_threaded this is possible and runs properly. Rails 1.2 also seems to add a scope argument to acts_as_nested_set.
To add acts_as_list methods see http://www.vaporbase.com/postings/List_methods_for_nested_sets