Breadcrumbs in Ruby on Rails

Michael Schmitz picture Michael Schmitz · Feb 17, 2010 · Viewed 30.6k times · Source

I'm slightly insecure about my breadcrumb solution. Names and links are defined in each controller action:

<a href="http://localhost:3000/">Home</a>
<% if defined? @l1_link %>
  > <a href="<%= @l1_link%>"><%= @l1_name %></a>
  <% if defined? @l2_link %>
    > <a href="<%= @l2_link%>"><%= @l2_name %></a>
  <% end %>
<% end %>

This way I can use:

@l1_link = user_path()

Question: As I am not that smart - could this kind of system lead to desaster somewhere down the road? Is this (grossly) inefficient?

Answer

Simone Carletti picture Simone Carletti · Feb 17, 2010

Breadcrumbs menu are a recurrent pattern in most Rails applications. To solve this issue, I created and released a plugin called breadcrumbs_on_rails.

You define your breadcrumbs in the controller

class MyController

  add_breadcrumb "home", root_path
  add_breadcrumb "my", my_path

  def index
    # ...

    add_breadcrumb "index", index_path
  end

end

and you render them in your view.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>untitled</title>
</head>

<body>
  <%= render_breadcrumbs %>
</body>
</html>

Even if you don't want to use a plugin, I encourage you to give it a look. It's open source and you can grab some idea for your app.