Why does my recursive method from helper not return every value?

I want to display a tree of categories managed with the gem ancestry.

I would like to use a helper which will recursively go through the tree and return the categories one by one, for 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) # to check if it goes here
      end
    end
    category.name
  end
end

The category argument is one of the root categories.

What should it return?

  • In the web page: It displays only the root level category Sport Beauty Automobile
  • In the console: Men Indoor Women Children Water sport Garage

If get them, then it means that the recursion works, but it does not. Why does it return only the first iteration?

Also I would 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 please give me your comments?

PS: I just found out (during adding tags) that I was using the word "recursivity" all along my searches but it doesn't exist, even if many people are using it on 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 that html is not interpreted and the same code is shown in the displayed webpage. I mean that I see

I probably missed something... maybe knowledge oO

Thx

6
задан Bachet 23 May 2011 в 07:43
поделиться