Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Awesome nested set plugin

Is there a simple way to display the entire nested set when using this plugin? What I would like to do is display an unordered list of root nodes with another unordered list inside each child that also contains children and so on?

Any advice appreciated.

Thanks.

like image 877
Dan Avatar asked Jan 13 '10 20:01

Dan


2 Answers

There are a few ways to do this. The simplest is to just start with the roots and parse each node and it's children. The first thing I'd do is make a partial for a the node markup:

_your_model.html.erb

<li>
  <%= your_model.name %>

  <% unless your_model.children.empty? %>
    <ul>
      <%= render your_model.children %>
    </ul>
  <% end %>
</li>

Next edit your view so that the first root nodes are rendered:

<ul>
  <% YourModel.roots.each do |node| %>
    <%= render node %>
  <% end %>
</ul>
like image 193
Jimmy Baker Avatar answered Oct 07 '22 18:10

Jimmy Baker


Using your_model.children will require another hit on the database each time it is encountered which is not preferable.

I have created a helper which helps generate the nested ul and li tags with only one database hit. You can modify this helper for your own needs:

https://github.com/collectiveidea/awesome_nested_set/wiki/How-to-generate-nested-unordered-list-tags-with-one-DB-hit

like image 35
Homan Avatar answered Oct 07 '22 16:10

Homan