Blog

Discover Our Blog

How to implement breadcrumbs functionality in Ruby on Rails app?

How to implement breadcrumbs functionality in Ruby on Rails app?

Breadcrumbs are graphical control element used as navigational aid in user interfaces. Today I am going to explain how it can be implemented in Ruby on Rails in simple steps as follows:

Step 1: Create a sample app using scaffold

Step 2: Add"breadcrumbs_on_rails" gem to the Gemfile and install it.

Step 3: Create a home.html.erb in articles for home page and route for it.

--> app/views/articles/home.html.erb


 

Welcome

This is the home page of Sample Article

<%= link_to "Articles", articles_path%>

--> config/routes.rb

root 'articles#home'

Breadcrumb00

Step 4: Add breadcrumb for home page.

In Articles Controller create method “add_breadcrum” to set the braedcrumb for home path like this:

--> app/controllers/articles_controller.rb

defadd_breadcrum

add_breadcrumb "Home".html_safe

end

For every view page set home page as the first breadcrumb in articles controller by the default using:

before_action :add_breadcrum

Step 5: Add breadcrumb for other pages of article like index, create, edit and show in articles controller by adding the line for breadcrumb as “add_breadcrumb ...........”.

--> app/controllers/articles_controller.rb

def index

@articles = Article.all

add_breadcrumb "Index".html_safe

end

Breadcrumb01

def new

@article = Article.new

add_breadcrumb "Index".html_safe

add_breadcrumb "Create".html_safe

end

Breadcrumb02

def edit

add_breadcrumb "Index".html_safe

add_breadcrumb "Edit: #{@article.title}".html_safe

end

Breadcrumb03

def show

add_breadcrumb "Index".html_safe

add_breadcrumb "Show: #{@article.title}".html_safe

end

Breadcrumb04

Step 6: To add seprator “/” and show breadcrumb to view page we will render the breadcrumb

<%= render_breadcrumbs :separator => " / " %>

Comments

Leave a comment: