Acts As Tree Category Display
I modified this post:
http://www.bigbold.com/snippets/posts/show/296
because the first one worked if you did stuff in your view to make the root categories come up, but I agree with the commenter that things should be contained to the helper - however I've managed to break the DRY rule in doing so. If anyone has any suggestions for a better way around this I'd love to hear it, so please comment. So anyway.. this should list your root categories ONLY and NOT your other sub-cats as well so that you have a very pretty little tree.
Slap this in your view:
<%= display_categories(@categories) %>
And put this in a helper file. You'll need it in the application helper most likely since you'll want to call it from multiple views.
def display_categories(categories)
ret = "<ul>"
for category in categories
if category.parent_id == 0
ret += "<li>"
ret += link_to category.name
ret += find_all_subcategories(category)
ret += "</li>"
end
end
ret += "</ul>"
end
def find_all_subcategories(category)
if category.children.size > 0
ret = '<ul>'
category.children.each { |subcat|
if subcat.children.size > 0
ret += '<li>'
ret += link_to h(subcat.name), :action => 'edit', :id => subcat
ret += find_all_subcategories(subcat)
ret += '</li>'
else
ret += '<li>'
ret += link_to h(subcat.name), :action => 'edit', :id => subcat
ret += '</li>'
end
}
ret += '</ul>'
end
end