Blog

Adding Breadcrumbs to Your Rails App

Mohammad Jassim
September 13, 2023

Breadcrumbs can be very useful when navigating to different locations on a web application, as well as to figure out where you are when you’ve clicked a series of links and gotten lost in the process.

In essence, a breadcrumb is simply a link to a page in a navigational structure preceded by links to previous pages in the hierarchy. These can simply be implemented by storing the links to an array and using helper methods to add/remove from this array as well as applying styling. On the other hand, it can be handy to use a plugin that already manages all this for you, especially if you’re feeling lazy. The most widely used gem I found to do this is breadcrumbs_on_rails. That’s it. The end.

Ok, so…maybe a few words in the epilogue.

Adding Breadcrumbs_on_rails

To start, add breadcrumbs_on_rails to your project’s Gemfile:


# Gemfile
gem "breadcrumbs_on_rails"

And then run bundle to install the dependencies.

Usage

It’s quite simple to create a breadcrumb navigation menu from here on. The call to add_breadcrumb method needs to be placed in your controllers. This method appends a new element to the breadcrumbs array. It accepts 2 arguments: the name of the breadcrumb and the target path. For example, say you have a controller called organizations, with the standard CRUD actions, you would end up with the following code:


  def new
    @organization = Organization.new
    add_breadcrumb "Organizations", :organizations_path
    add_breadcrumb "New"
  end
  def index
    …
    add_breadcrumb "Organizations", :organizations_path
    …
  end
  def show
    add_breadcrumb("Organizations", :organizations_path)
    add_breadcrumb(@organization.name)
  end
  def edit
    …
    add_breadcrumb "Organizations", :organizations_path
    add_breadcrumb(@organization.name)    
    add_breadcrumb "Edit", edit_organization_path(@organization)
  end

Next, you’re ready to render the breadcrumbs menu in your views, and to do that you can use the render_breadcrumbs helper.

A good approach is to create a layout that can be shared across the application like so:


# app/views/shared/_breadcrumbs.html.erb

Finally, render this layout in your application layout, for example:


 # app/views/layouts/application.html.erb
    

The outcome of all this is a clickable breadcrumbs menu rendered on the top of the page:

breadcrumb2

Conclusion

breadcrumbs_on_rails is one of many gems available to help inject breadcrumbs easily into your Ruby on Rails application. I found it simple enough to add the navigation menu using this gem and also to choose and apply the styling I wanted. If you follow the steps highlighted in this article you will find that that’s really all you need to add basic breadcrumbs functionality to your Ruby on Rails site. Enjoy!

Source: [https://github.com/weppos/breadcrumbs_on_rails]