DEV Community

Michael Lee 🍕
Michael Lee 🍕

Posted on

3

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
jsrn profile image
James

This is handy, thank you!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more