Tree menu using ancestry in rails

859 Views Asked by At

according to this answer https://stackoverflow.com/a/11335283/2397494 i'm trying to make tree menu for my appliction

this answer working only for root and first children. I'm looking for suggestion to transform this code, work well with n childrens.

<ul id="menu">
  <% Hub.roots.each do |category| %>
     <li> <%= link_to h(category.title), category %>
        <% unless category.children.empty? %>
           <ul id="sub-menu"> 
             <% category.children.each do |subcategory| %>
                <li><%= link_to h(subcategory.title), subcategory %></li>
             <% end %>
           </ul>
        <% end %>
     </li>
  <% end %>
</ul>
1

There are 1 best solutions below

0
On
  <% Hub.roots.each do |category| %>
    <div> <%= link_to h(category.title), category %>
      <% if category.children.present? %>
      <div id="submenu">
        <%= render 'hubs/sub', category: category %>
      </div>
      <% end %>
    </div>
  <% end %>

partial _sub

<ul>
  <% category.children.each do |sub| %>
    <li>
      <%= link_to_unless_current sub.title, sub %>
      <%= render 'hubs/sub', category: sub %>
    </li>
  <% end %>
</ul>

and css

#submenu > ul, ol {
  margin-right: 20px;
  li {
    font-size: 11px;
    margin: 4px 0;
    margin-bottom:-5px !important;
  }
  ul, ol {
    font-size: 11px;
    margin: 0;
    padding-left: 16px;
    margin-bottom:-5px !important;
    li {
      margin: 4px 0;
    }
  }
}