Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Render tree within a single sql query
def render_tree(nodes = [])
stack = []
html = ""
nodes.each do |node|
if stack.empty?
html << start_tag(node)
stack.push(node)
next
end
if stack.last.lft < node.lft && node.lft < stack.last.rgt
if node.leaf?
html << node_tag(node)
else
html << start_tag(node)
stack.push(node)
end
if node.rgt + 1 == stack.last.rgt
html << end_tag
stack.pop
end
else
html << end_tag
stack.pop
redo
end
end
content_tag(:ul, html.html_safe, :id => "category-tree")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment