Reputation: 467
I'm using the ancestry gem in order to create categories, subcategories, sub-subcategories and so on. Everything is working just fine, I can create a category, then create a subcategory which belongs to this category and then create a sub-subcategory for the subcategory and so on. The only issue I'm having is that I cant figure out how to show all the categories with each full tree from root until the very last subcategory inside a view.
Currently I have the following setup and I'm getting only up to the subcategory:
Inside the controller: @categories = Category.where(ancestry: nil).order('name ASC')
Inside the view :
<% @categories.in_groups_of(3) do |category| %>
<div class="row">
<% category.each do |item| %>
<div class="col-md-4">
<% if item.present? %>
<ul>
<li><%= (item.name) %>
<%= link_to edit_category_path(item) do %><i class="fas fa-edit"></i><% end %>
<%= link_to new_subcategory_path(ancestry: item) do %><i class="fas fa-plus-circle"></i><% end %>
<%= link_to category_path(item), :method => :delete, data: { confirm: "Are you sure?" } do %><i class="far fa-trash-alt"></i><% end %>
<% unless item.children.empty? %>
<ul>
<% item.children.sort_by(&:name).each do |subcategory| %>
<li>
<%= subcategory.name %>
<%= link_to edit_category_path(subcategory) do %><i class="fas fa-edit"></i><% end %>
<%= link_to new_subcategory_path(ancestry: subcategory) do %><i class="fas fa-plus-circle"></i><% end %>
<%= link_to category_path(subcategory), :method => :delete, data: { confirm: "Are you sure?" } do %><i class="far fa-trash-alt"></i><% end %>
</li>
<% end %>
</ul>
<% end %>
</li>
</ul>
<% end %>
</div>
<% end %>
</div>
<% end %>
Then I found this solution, which does show the root until the very last subcategory. But I cant really use this solution, since I have a few link_to
that I want to show inside the loop(as you can see above). Any ideas how I can make the above solution show the root until the very last subcategory?
@items_tree = Category.all.arrange
def nested_groups(groups)
s = content_tag(:ul) do
groups.map do |group, sub_groups|
content_tag(:li, (group.name + nested_groups(sub_groups)).html_safe)
end.join.html_safe
end
end
Upvotes: 1
Views: 647