how to loop through an acts_as_tree or ancestry hierarchy

290 Views Asked by At

I'd like to take a structure like this where each header has a headers and items array:

header
  header
    \item
     item
     item
   header
     header
       item
header
  item
  item  

and make it into a list like this:

header
header
item
item
item
header
header
item
header 
item
item

I need to be able to handle nested like 6 deep. Right now, I just do an each loop and check for does it have items or does it have headers? But I really don't want to have 6 levels of this- I would like to do some while loop but just not sure how to do it.

1

There are 1 best solutions below

0
On

I found lots of sites pointed to a website which is now offline. Lucky archive.org is there to help! [link]

I have implemented so. A helper:

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 subcat.name, subcat
        ret += find_all_subcategories(subcat)
        ret += '</li>'
      else
        ret += '<li>'
        ret += link_to subcat.name, subcat
        ret += '</li>'
      end
    }
    ret += '</ul>'
    ret.html_safe
  end
end

And then in the view:

ul
  - for category in @categories
    li
      = link_to category.name, category
      = find_all_subcategories(category)

Just check the attribute you use for your model. In my case it was name.

So, maybe late, but could help others.