For a long time, I was looking for a good clean solution on how to create active links on the Mirror Communications website. I came across a good solution a while back when I took a course from Jorden Hudgens on Udemy.

Therefore, this implementation is built off his guide with a minor tweak. Essentially, I needed a solution which takes in multiple CSS classes, as the Mirror Communications website uses two different page headers with different styling.

This implementation relies on the current_page? method in Rails, which you can learn more about by clicking here.

Alright, let's get started by adding a helper method


def current?(key, path)
   "#{key}" if current_page? path
   # We use string interpolation "#{key}" here to access the CSS classes we are going to create.

# Basically, we are taking two arguments here, the key is the active class we are going to create, and the path is the link itself. 

Now let's create two different active classes


.active {
   color: #fff;

.secondary_active {
   color: #000;

Ok, let's now create the links themselves

# Inside of your view template.

     <%= link_to "Blog", posts_path, class: "#{current? "active", posts_path}"  %>

# Using a different class:
     <%= link_to "Blog", posts_path, class: "#{current? "secondary_active", posts_path}"  %>

# Using a normal link:
     <%= link_to "Blog", "/blog", class: "#{current? "secondary_active", posts_path}"  %>

And that's it, I hope this helps you out.

Cheers, Brian