Create sidebar using partials – Ruby on Rails

This post shows how to create sidebar using partials.
Rails version: 4.2.5
Assuming that Bootstrap is installed.


Edit application controller
use before_action method to pass variables to layout. (application.html.erb)
app/controllers/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">
      <%= render partial: 'categories/sidebar' %>
    </div>                 
  </div>
</body>
</html>

Create partial file
app/views/categories/_sidebar.html.erb

<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>

Leave a Reply

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