I want to display a tree of categories driven by a gem family tree.
I would like to use a helper element that will recursively traverse the tree and return categories one by one, at the moment without html tags or content.
module CategoriesHelper def display_tree(category) if category.has_children? category.children.each do |sub_category| display_tree(sub_category) puts(sub_category.name)
The category argument is one of the root categories.
What should he return?
- On the web page: It only displays the
Sport Beauty Automobile root level category - In console:
Men Indoor Women Children Water sport Garage
If you get them, then recursion works, but it doesnβt. Why does it return only the first iteration?
I would also like to get them in the following order:
root/child/child-of-child
but if I want to return category.name , it should be in the last position.
Could you give me your comments?
PS: I just found out (when adding tags) that during my searches I used the word "recursion", but it does not exist, even if many people use it in stackOveflow; o)> "recursion", but still I'm stuck
** EDIT **
Now I use this code:
module CategoriesHelper def display_tree(category) tree = "<div class =\"nested_category\">#{category.name}" if category.has_children? category.children.each do |sub_category| tree += "#{display_tree(sub_category)}" end end tree += "</div>" end end
which gives me:
<div class ="nested_category">Sport <div class ="nested_category">Men</div> <div class ="nested_category">Women <div class ="nested_category">Indoor</div> </div> <div class ="nested_category">Children</div> <div class ="nested_category">Water sport</div> </div> <div class ="nested_category">Beauty</div> <div class ="nested_category">Automobile <div class ="nested_category">Garage</div> </div>
But this html is not interpreted, and the same code is displayed on the displayed web page. I mean i see
I probably missed something ... maybe knowledge oO
thanks