Improve Your Rails App's Navigation with link_to_unless_current

In Rails, the link_to helper is used to generate HTML links. But what if you want a link to only appear if the current page isn’t the one it points to? That’s where link_to_unless_current comes in.

How it works

link_to_unless_current works the same way as link_to, but with one important difference: it only generates a link if the current page isn’t the one it points to. If the current page is the same as the link, it only generates the text of the link.

Examples

1. Navigation menu

Consider a navigation menu with links to “Home”, “About”, and “Contact”. Using link_to, the code would look like this:

1
2
3
4
5
<ul>
  <li><%= link_to "Home", root_path %></li>
  <li><%= link_to "About", about_path %></li>
  <li><%= link_to "Contact", contact_path %></li>
</ul>

With link_to_unless_current, we can highlight the current page:

1
2
3
4
5
<ul>
  <li><%= link_to_unless_current "Home", root_path %></li>
  <li><%= link_to_unless_current "About", about_path %></li>
  <li><%= link_to_unless_current "Contact", contact_path %></li>
</ul>

On the “Home” page, the “Home” link will be just text, while the other links will be real links.

2. “Back” button

On a product details page, we can use link_to_unless_current to create a “Back” button that takes the user to the product listing page:

1
<%= link_to_unless_current "Back", products_path %>

If the user is on the product details page, the “Back” button will be a real link. If they are already on the product listing page, the button will be just text.

3. Conditional links

link_to_unless_current can also be used to create conditional links. For example, we can show a “Login” link only if the user is not logged in:

1
2
3
<% if !current_user %>
  <%= link_to_unless_current "Login", login_path %>
<% end %>

link_to_unless_current is a useful helper for generating dynamic links in Rails. It can be used to highlight the current page, create “Back” buttons, and conditional links. It improves the usability of the interface, facilitates navigation and avoids redundant links.