Robert Mannl wrote:
> b) Any ideas how could print out an acts_as_nested_tree list like a tree
> in HTML? I.e. I have only managed to print out
> but had no success with printing out a hireachial tree like this
>
> Fruits
> - Banana
> - Strawberry
> Sweets
> - Chocolate
> - Caramel
This is not entirely easy and my solution has a few drawbacks, but I
thought that it might get you started anyway. Also note that I''m using
acts_as_tree and not sure if that is the same as acts_as_nested_tree.
This is my view:
> <% process_category = lambda do |parent_id, non_top| %>
> <% categories = @categories[parent_id] %>
> <% unless categories.to_a.empty? then %>
> <ul class="navigation <%= non_top ? '''' :
''top-'' %>categories">
> <% for category in categories do %>
> <%
> link_target = if category == Shop.main_category then
> { :controller => ''shop'' }
> else
> { :controller => ''categories'', :action
=> ''show'', :id => category.title }
> end
> %>
> <li>
> <%= link_to category.title, link_target %>
> <% process_category.call(category.id, true) %>
> </li>
> <% end %>
>
> <% admin do %>
> <% unless non_top then %>
> <li><%= link_to ''Ohne Zuordnung'',
:controller => ''products'', :action =>
''unassociated'', :id => nil %></li>
> <li><%= link_to ''Unsichtbar'',
:controller => ''products'', :action =>
''invisible'', :id => nil %></li>
> <li><%= link_to ''Neue Kategorie'',
:controller => ''categories'', :action =>
''new'', :id => nil %></li>
> <% end %>
> <% end %>
> </ul>
> <% end %>
> <% end %>
>
> <% process_category.call(0, false) %>
Where @categories = Category.all_by_parent in the controller.
Category.all_by_parent is defined as:
> def self.all_by_parent()
> result = Hash.new { |hash, key| hash[key] = [] }
> find_all.each do |category|
> result[category.parent_id] << category
> end
> result.each do |key, children|
> result[key] = children.sort_by { |category| category.category_no }
> end
> return result
> end
The drawbacks I was talking about are mainly that this does quite a lot
at the client-side to avoid needing to do more than one query. I think
that that is still better than triggering a lot of queries, but it has
performance implications nevertheless. Perhaps acts_as_nested_set would
be a better choice in this case.