Topic: Recursive Fun with Children

Hey guys,

any pointers for refactoring this part of the main nav in case an admin makes more than 3 levels of categories?

Model Category, foreign key, parent and child => foreign key is parent_id

<% @categories = Category.parents %>
        <% @categories.each do |category| %>
        <li>
            <%= link_to category.title, category %>
            <% unless category.children.empty? %>
                <ul>
                    <% category.children.each do |subnav| %>
                        <li>
                            <%= link_to subnav.title, subnav %>
                            <% unless subnav.children.empty? %>
                                <ul>
                                    <% subnav.children.each do |subsub| %>
                                        <li><%= link_to subsub.title, subsub %></li>
                                    <% end %>
                                </ul>
                            <% end %>
                        </li>
                    <% end %>
                </ul>
            <% end %>
        </li>
        <% end %>

Last edited by rlonac (2008-07-08 22:22:56)

Re: Recursive Fun with Children

Absolutely.

# your existing view (you may want to assign @categories = Category.parents in your controller)
<%= render :partial => "category", :collection => Category.parents %>

# app/views/_category.html.erb
<li>
  <%= link_to category.title, category %>
  <% unless category.children.empty? %>
  <ul>
    <%= render :partial => "category", :collection => category.children %>
  </ul>
</li>