Есть хороший gem awesome_nested_set, с помощью которого можно создавать деревья сущностей в вашей БД. К сожалению, хелперов, чтобы отобразить на странице древовидный ul — li список в этом геме нет. Здесь я приведу пример хелпера, который отрендерит древо Nested set в виде правильного ul — li списка:
module ApplicationHelper #... def nested_tree(nodes, link) current_depth = 0 counter = 0 node_depth = 0 result = "<ul>" nodes.each do |n| node_depth = n.depth node_id = n.id node_title = n.name if node_depth == current_depth result += "" if counter > 0 elsif node_depth > current_depth result += "</ul><ul>" current_depth += (node_depth - current_depth) elsif node_depth < current_depth result += ("</li></ul>"*(current_depth - node_depth)) + "" current_depth -= (current_depth - node_depth) end result += "<li " result += ' class="root"' if node_depth == 0 path = link + "(n)" result += '><a href="' + eval(path) + '" title="' + h(node_title) + '">' + h(node_title) + '</a>' counter += 1 end result += '</li>' * node_depth result += '' end end |