Determine current route in Rails

Written on March 6, 2019

Let’s say you’re building a sweet navigation in your Rails application and the design you’re implementing shows that you’ve got different states that have different visual cues.

Those states might be inactive, hovering and active or current. Inactive and hovering seems pretty straight forward, you can do all that in CSS.

.Nav-Item {
  // Styles for the "inactive" nav item state
  // would go here.
}

.Nav-Item:hover {
  // Styles for the "hover" nav item state
  // would go here.
}

But the active or nav item state that indicates you’re currently on the same page as an item in the nav isn’t a simple CSS solution. To solve this, you’ll need to use a built-in Rails helper called current_page?.

With the current_page? helper you can pass it things like a relative or absolute path that you’d like to check or you can even pass it actions and controllers with parameters for it to check. Doing so will return either a true or false.

How this could look in your mark up is this,

<%= link_to({ controller: 'page', action: 'about' }, { class: "Nav-Item #{'is-current-page' if current_page?(controller: 'page', action: 'about')}" }) do %>
  About Us
<% end %>

I’m using the current_page? helper inside a link_to helper block. Specifically it is being passed to the class attribute where it is saying, if the current page current_page? is the same as the page handled by the about action in the page controller, then add the value of is-current-page to the class attribute.

Now I could have this in my CSS,

.Nav-Item {
  // Styles for the "inactive" nav item state
  // would go here.
}

.Nav-Item:hover {
  // Styles for the "hover" nav item state
  // would go here.
}

.Nav-Item.is-current-page {
  // Styles for the nav item that corresponds
  // with the current page the user is viewing
}

Now we’re able to handle inactive, hovering and current page states in a Rails application nav.

Stay in touch

Thanks for reading this article. I'd love to stay in touch and share articles like this one in your inbox. Sign up for my newsletter.