(first posted: Feb 21, 2008)
(2331 Reads)
keywords: acts_as_list acts_as_nested_set
Permalink
List methods for nested sets
I had been using acts_as_tree together with acts_as_list to make ordered nested lists. Recently I replaced acts_as_tree with the better_nested_set plugin, a formidable replacement that is much more efficient in database queries (it pulls the whole tree from the database at once). The nested set is also ordered, so there's no need for acts_as_list.
Unfortunately better_nested_set lacks the list methods provided by acts_as_list. Here's a module that provides them. It treats each branch of a tree as its own list, thus these methods are scoped by the local root.
I haven't bothered to make this a plugin. Just create a file lib/nested_set_list.rb and paste this code:
module NestedSetList
def first?
parent.nil? or parent.lft==self.lft-1
end
def last?
parent.nil? or parent.rgt==self.rgt+1
end
def higher_item
list = self_and_siblings
i = list.index(self)
i==0 ? self : list[ i-1 ]
end
def lower_item
list = self_and_siblings
i = list.index(self)
i==list.size-1 ? self : list[ i+1 ]
end
def move_higher
move_to_left_of( higher_item ) if higher_item
end
def move_lower
move_to_right_of( lower_item ) if lower_item
end
def move_to_top
move_to_left_of( self_and_siblings.first )
end
def move_to_bottom
move_to_right_of( self_and_siblings.last )
end
end
In your model, be sure to include it
acts_as_nested_set
include NestedSetList




List methods for nested sets
Posted by: Dr. Serge on March 10, 2008 10:57 AM#