Saturday, October 1, 2016

Making breadcrumbs navigation in Rails Apps

Making breadcrumbs navigation in Rails Apps
Making breadcrumbs in rails apps is quite simple. By using gem breadcrumbs_on_rails, breadcrumbs show up right away.
Only Master-details navigation needed to be carefully designed in order to reveal the relationship between the two models. Please follow the Tips below.

Installation

Add this line to Gemfile:
gem "breadcrumbs_on_rails"
then:
bundle install

Controller Setting

Add code below to the controller
class OrdersController < ApplicationController
  add_breadcrumb 'home', :root_path
  add_breadcrumb 'orders', :orders_path

  def show
    @orderdetails = @order.orderdetails
    add_breadcrumb @order.id, order_path
  end
end  
In most cases, adding breadcrumbs navigation only to ‘index’, show’ and ‘edit’ page.

Add Breadcrumbs in View

And then, add render_breadcrumbs helper to the application view file.
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    :
  </head>
  <body>
    <div class="container" >
         :
      <%= render_breadcrumbs %>
      <%= yield %>
    </div>
  </body>
</html>
And it’s done!

Tips

Put ‘home’ navigation code in ApplicationController

The ‘home’ navigation need to be shown in every page of the app. So the code of breadcrumb is necessary to move from all controllers to application controller.
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  add_breadcrumb 'home', :root_path
end

Using customized separator

I use “/” instead of “>>” as the separator. Just assign the separator as follows: (in Bootstrap style)
<%= render_breadcrumbs tag: :li, separator: "" %>

Master-Details navigation

The breadcrumb navigation should show the master-detail relationship between two models. For example, a order may have many order details. The navigation should be something like this:
home / orders / 1 / orderdetails / 2 
The solution is to add three lines of code in action ‘edit’ of the controller for showing the last three breadcrumb above.
def edit
  @order = Order.find(@orderdetail.order_id)
  add_breadcrumb @order.id, order_path(@order)
  add_breadcrumb 'orderdetails', order_path(@order)
  add_breadcrumb @orderdetail.id, edit_order_orderdetail_path
end

Twitter Bootstrap Style

Add class='breadcrumb' and it’s done!
<div class='breadcrumb'>
  <%= render_breadcrumbs tag: :li, separator: "" %>
</div>

No comments:

Post a Comment