#162 Tree-Based Navigation (revised)
If your Rails app is content-heavy, consider organizing it in a tree menu structure. Here I show how to add top-level tabs, nested links in a side bar, and breadcrumbs to go up the hierarchy.
- Download:
- source code Project Files in Zip (42.6 KB)
- mp4 Full Size H.264 Video (18.5 MB)
- m4v Smaller H.264 Video (10.5 MB)
- webm Full Size VP8 Video (14.1 MB)
- ogv Full Size Theora Video (22 MB)
Browse_code
Browse Source Code
Resources
- Active Record Nesting on Ruby Toolbox
- Ancestry
- Episode 262: Trees with Ancestry
- Episode 90: Fragment Caching (revised)
terminal
rails new cms cd cms rails g scaffold page name content:text ancestry:string:index rake db:migrate
Gemfile
gem 'ancestry'
pages/show.html.erb
<% content_for :title, @page.name %> <ul id="menu"> <% Page.roots.each do |page| %> <li><%= link_to page.name, page, class: ("active" if @page.root == page) %></li> <% end %> </ul> <div id="submenu"> <%= render 'submenu_pages', pages: @page.root.descendants.arrange %> </div> <div id="breadcrumbs"> <% @page.ancestors.each do |page| %> <%= link_to page.name, page %> > <% end %> </div> <h1><%= @page.name %></h1> <%= simple_format @page.content %>
pages/_submenu_pages.html.erb
<ul> <% pages.each do |page, children| %> <li> <%= link_to_unless_current page.name, page %> <%= render 'submenu_pages', pages: children if children.present? %> </li> <% end %> </ul>
layouts/application.html.erb
<title><%= content_for?(:title) ? yield(:title) : "CMS" %></title>
models/page.rb
class Page < ActiveRecord::Base attr_accessible :parent_id, :content, :name has_ancestry end
loading