ruby on rails - Group records by parent id -


i have following records in 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 show them in list so:

<ul> <% @pages.each |page| %>   <li>     <%= page.parent.title rescue '' %><br>     <%= page.permalink %>   </li> <% end %> </ul> 

this creates list like:

<ul>     <li>about<br>/about</li>     <li>team<br>/about/team</li>     <li>cameron<br>/about/team/cameron</li> </ul> 

but want create nested list following, uses parent_id 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 quick , easy way group them in controller?


the best idea have come in controller:

@pages = page.where(parent_id: nil)

and in view:

<% @pages.each |page| %>     <%= render 'page_row', :page => page, :sub => 0 %>     <% page.pages.each |page| %>         <%= render 'page_row', :page => page, :sub => 1 %>         <% page.pages.each |page| %>             <%= render 'page_row', :page => page, :sub => 2 %>             <% page.pages.each |page| %>                 <%= render 'page_row', :page => page, :sub => 3 %>             <% end %>         <% end %>     <% end %> <% end %> 

using partial create nest:

<%   $i = 0   $num = sub   prefix = ''   while $i < $num     prefix += '---'     $i +=1   end %> <li> <%= prefix %> <%= page.parent.title rescue '' %><br>         <%= page.permalink %> </li> 

but manually looping have been doing, limits nesting 4 levels deep , code isn't nice.

how can achieve same result without manually looping create nested view of pages?

i think you're on right track instead of looping fixed number of times entire view should recursive.

in controller: @top_level_pages = page.where(parent_id: nil)

in view

<%= render 'pages', pages: @top_level_pages, level: 0 %> 

in pages partial

<% pages.each |page| %>   <li>     <%= '-' * level %><%= page.name %><br>     <%= page.permalink %>   </li>   <%= render 'pages', pages: pages.pages, level: level + 1 %> <% end %> 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -