Sergey K
Sergey K

Reputation: 5107

Rails simple navigation, nested set

I built navigation menu using simple navigation and built nested categories which i display in this menu.

navigation.rb code:

  navigation.items do |primary|
    Category.roots.map do |root|
      primary.item ":root_#{root.id}", root.title, category_path(root) do |secondary|
        root.descendants.map do |desc|
          secondary.item ":desc_#{desc.id}", desc.title, category_path(desc)
        end
      end
    end
  end

The question is: how can i display all the levels of categories in my menu. That code does only with two level nesting.

Thank in advance

Upvotes: 0

Views: 2342

Answers (2)

Arun Kumar Arjunan
Arun Kumar Arjunan

Reputation: 6857

Please take a look at how refinery-cms does this.

The _menu.html.erb is close to what you have. In addition to that it has another partial called _menu_branch.html.erb that renders the submenus of the menu recursively.

https://github.com/resolve/refinerycms/blob/master/core/app/views/refinery/_menu.html.erb https://github.com/resolve/refinerycms/blob/master/core/app/views/refinery/_menu_branch.html.erb

Code cut from github:

_menu.html.erb

<nav id='<%= dom_id %>' class='<%= css %>'>
  <ul>
    <%= render :partial => '/refinery/menu_branch', :collection => roots,
               :locals => {
                 :hide_children => hide_children,
                 :sibling_count => (roots.length - 1),
                 :apply_css => true #if you don't care about class='first' class='last' or class='selected' set apply_css to false for speed.
               } -%>
  </ul>
</nav>

_menu_branch.html.erb

<li<%= ['', css].compact.join(' ').gsub(/\ *$/, '').html_safe %>>
<%= link_to(menu_branch.title, main_app.url_for(menu_branch.url)) -%>
  <% if (children = menu_branch.children unless hide_children).present? -%>
    <ul class='clearfix'>
      <%= render :partial => '/refinery/menu_branch', :collection => children,
                 :locals => {
                   :apply_css => local_assigns[:apply_css],
                   :hide_children => !!hide_children
                 } -%>
    </ul>
  <% end -%>
</li>

Upvotes: 2

Andrew Lank
Andrew Lank

Reputation: 1617

You will have to use recursive if this helps at all, you can see an example here: Recursive Rails Nested Resources

Upvotes: 0

Related Questions