Я ищу, чтобы отобразить дерево html из вложенных данных набора.Создание дерева из вложенного набора
Поскольку отображаемое дерево не всегда отображает все ветви, то листовые узлы не могут быть идентифицированы путем вычитания значений lft & rgt.
1 Drinks 27
/ | \
2 Coffee 3 4 Tea 20 21 Milk 26
/ \
5 Black 8 9 Green 19
/ \
10 China 14 15 Africa 18
Я искал адаптировать следующий код: How to render all records from a nested set into a real html tree
Решение:
Счастлив получить предложения по улучшению кода :)
def tree_from_set(set, start_level)
buf = "<ul>"
parent = []
prev = set[start_level]
set[start_level+1..-1].each do |node|
if node.lft.between?(prev.lft, prev.rgt)
# Previous was the parent
buf << open_parent_tag(prev)
parent.push(prev)
else
if node.lft.between?(parent.last.lft, parent.last.rgt)
#Previous was a child
buf << leaf_tag(prev)
else
buf << leaf_tag(prev)
begin
buf << "</ul></li>"
parent.pop
end until parent.empty? or node.lft.between?(parent.last.lft, parent.last.rgt)
end
end
prev = node
end
buf << leaf_tag(prev)
begin
buf << "</ul></li>"
parent.pop
end until parent.empty?
buf << "</ul>"
buf.html_safe
end
def open_parent_tag(node)
%{ <li>
#{link_to(node.name, node)}
<ul>
}
end
def leaf_tag(node)
content_tag(:li, link_to(node.name, node))
end
Попробуйте использовать это: http://stackoverflow.com/questions/1372366/how-to-render-all-records-from-a-nested-set-into-a- реальный HTML-дерево –