Created
March 4, 2010 22:46
-
-
Save lwille/322213 to your computer and use it in GitHub Desktop.
Single DB query tree generation with awesome_nested_set
This file contains hidden or 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
module ApplicationHelper | |
# Mixin for tree generation based on a nested set, just place this in your application_helper.rb | |
module TreeMethods | |
attr_accessor :child_nodes | |
attr_accessor :parent_node | |
def after_initialize | |
@child_nodes = [] | |
@parent_node = nil | |
end | |
def recursive_tree nodes=nil, level=0 | |
if @child_nodes.nil? | |
after_initialize | |
end | |
nodes = self_and_descendants if nodes.nil? | |
nodes.shift unless nodes.first.parent_node.nil? | |
nodes.each do |node| | |
if node.id!=id && node.parent_id == id | |
node.extend TreeMethods | |
@child_nodes << node | |
node.recursive_tree nodes, level+1 | |
end | |
end | |
self | |
end | |
end | |
def nested_tree base | |
unless base.nil? | |
if base.is_a?(ActiveRecord::Base) && base.respond_to?(:self_and_descendants) | |
base.extend TreeMethods;base.recursive_tree | |
elsif base.is_a?(Class) && base.respond_to?(:acts_as_nested_set) | |
base.roots.collect{|c| c.extend TreeMethods;c.recursive_tree} unless base.roots.nil? | |
end | |
end | |
end | |
end |
This file contains hidden or 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
render :partial=>category.child_nodes |
This file contains hidden or 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
@categories = nested_tree Category # calling with Class | |
@categories = nested_tree Category.root # calling with Instance | |
# or just try it on the console: | |
helper.nested_tree Category |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment