RailsCasts - Ruby on Rails Screencasts

RailsCasts Pro episodes are now free!

Learn more or hide this

Tree-Based Navigation (revised)

#162 Tree-Based Navigation (revised)

Dec 01, 2012 | 10 minutes | Active Record, Views, Plugins
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.
Click to Play Video ▶
Tweet
  • 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

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 %> &gt;
 <% 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

AltStyle によって変換されたページ (->オリジナル) /