DEV Community

Michael Lee 🍕
Michael Lee 🍕

Posted on

Determine the current route in Rails

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.
}
Enter fullscreen mode Exit fullscreen mode

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 %>
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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


Originally posted on michaelsoolee.com.

Thanks for taking the time to read this article! I'd love to stay in contact and send you tips on programming and design and making side projects through my newsletter. Click here to sign up.

Top comments (1)

Collapse
 
jsrn profile image
James

This is handy, thank you!