How to create Sidebar – Ruby on Rails

This post shows how to create sidebar by editing layout view. (application.html.erb)
Rails version: 4.2.5
Assuming that Bootstrap is installed.

Edit application controller
use before_action method to pass variables to application.html.erb
application_controller.rb

class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception
  before_action :set_page

  def set_page
    @categories = Category.all
  end
end

Edit layout
application.html.erb

<!DOCTYPE html>
<html>
<head>
  ...
</head>
<body>
  <div class="container">
    <ul class="nav nav-tabs">
      ...
    </ul>
    
    <div class="col-md-10">
      <%= yield %>
    </div>

    <div class="col-md-2">   <!--sidebar from here-->
      <h3>Categories</h3>
      <%= link_to "New Category", new_category_path, class: 'btn btn-success' %>
      <div class="row">
        <br> 
        <% @categories.each do |category| %>
             <div class="media">
               <div class="media-body">
                 <h5 class="media-heading">
                   <%= link_to category.name, category %>
                 </h5>
               </div>
             </div>
        <% end %>
      </div>
    </div>                 <!-- sidebar up to here-->
  </div>
</body>
</html>

 

Leave a Reply

Your email address will not be published. Required fields are marked *