I have the following records in my Rails app:
id: 1
name: 'About'
slug: 'about'
permalink: '/about'
parent_id: null
id: 2
name: 'Team'
slug: 'team'
permalink: '/about/team'
parent_id: 1
id: 3
name: 'Cameron'
slug: 'cameron'
permalink: '/about/team/cameron'
parent_id: 2
And I show them in a list like so:
<ul>
<% @pages.each do |page| %>
<li>
<%= page.parent.title rescue '' %><br>
<%= page.permalink %>
</li>
<% end %>
</ul>
This creates a list like:
<ul>
<li>About<br>/about</li>
<li>Team<br>/about/team</li>
<li>Cameron<br>/about/team/cameron</li>
</ul>
But I want to create a nested list like the following, which uses the parent_id to group them up.
<ul>
<li>About<br>/about</li>
<li>-- Team<br>/about/team</li>
<li>---- Cameron<br>/about/team/cameron</li>
</ul>
Is there a quick and easy way to group them up in the controller?
The best idea I have come up with is to do this in the controller:
@pages = Page.where(parent_id: nil)
And then this in the view:
<% @pages.each do |page| %>
<%= render 'page_row', :page => page, :sub => 0 %>
<% page.pages.each do |page| %>
<%= render 'page_row', :page => page, :sub => 1 %>
<% page.pages.each do |page| %>
<%= render 'page_row', :page => page, :sub => 2 %>
<% page.pages.each do |page| %>
<%= render 'page_row', :page => page, :sub => 3 %>
<% end %>
<% end %>
<% end %>
<% end %>
Using a partial to create the nest:
<%
$i = 0
$num = sub
prefix = ''
while $i < $num do
prefix += '---'
$i +=1
end
%>
<li>
<%= prefix %> <%= page.parent.title rescue '' %><br>
<%= page.permalink %>
</li>
But by manually looping like I have been doing, it limits the nesting to only 4 levels deep and the code isn't very nice.
How can I achieve the same result but without manually looping to create the nested view of pages?