5

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.

Adam Lassek
  • 35,156
  • 14
  • 91
  • 107
Dan
  • 703
  • 1
  • 7
  • 11

3 Answers3

4

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>
Jimmy Baker
  • 3,215
  • 1
  • 24
  • 26
  • I think you had a couple of typos there buddy. I think it would be <%= render 'partial_name', :collection => your_model.children %> inside of the partial; and in the outermost ul, you would do <%=render 'partial_name', :collection => YourModel.roots %> and completely get rid of the each. – jacortinas Jan 15 '10 at 05:03
  • Fixed the inner render to your_model.children. If you're using a newer version of rails you do not need to specify the name of the partial as long as you give it _the_name_of_your_model.html.erb. You also don't have to to pass in :collection. Rails will determine if it's a single instance or an array of objects. – Jimmy Baker Jan 15 '10 at 16:28
4

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

Homan
  • 25,618
  • 22
  • 70
  • 107
0

You can get the whole set with one query: Category.order("lft ASC")

And if you have :depth column, voila! One query for it all, just write your view to use :depth.

Mirko
  • 5,207
  • 2
  • 37
  • 33
  • No need to :depth column. Awesome nested set plugin has level method. – xaph Dec 15 '11 at 05:17
  • 1
    each call of level method query db :( – Vlad Mar 14 '12 at 00:33
  • Using [`each_with_level(objects)`](https://github.com/collectiveidea/awesome_nested_set/commit/9fcaaff3d6b351b11c4b40dc1f3e37f33d0a8cbe) should avoid multiple queries. – fractious Feb 08 '13 at 12:24