Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Rails helper to find the current path

I am trying to make a helper that adds Bootstrap "active" class to nav tabs on current page in browser. Problem is that I have categories and their subcategories, so I want categories tab to be active also when current page is a subcategory of that category.

This works:

  def active?(category)
    "active" if current_page?(category_path(category) || category_subcategory_path(category, 1))
  end

But as you see I hardcoded the subcategory id - 1 (just to test it works). I thought I could just pass category.subcategory instead of 1, but then I get undefined subcategory for category with id 1 because my categories table dont have any reference to subcategories (only subcategories table has a category_id row), so I guess I should define subcategory somehow in Categories controller, but how?

Also thought to grab the last segment of URI (http://localhost:3000/categories/2/subcategories/5), but it doesn't look as a convenient way for this.

   <% @categories.each do |cat| %>
     <li class="<%= active?(cat) %>">
       <%= link_to cat.name.titleize, category_path(cat) %></td>
     </li>
   <% end %>
   <% @category.subcategories.each do |subcategory| %>
     <li>
       <%= link_to subcategory.name.titleize, category_subcategory_path(@category, subcategory) %></td>
     </li>
   <% end %>

Upvotes: 0

Views: 374

Answers (2)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Solved it with:

  def active?(category)
    "active" if
      current_page?(category_path(category)) || 
      current_page?(category_subcategory_path(controller: 'subcategories', action: 'show', category_id: category))
  end

Upvotes: 1

dimitry_n
dimitry_n

Reputation: 3019

Add the following method to your Category model:

def has_child?(subcat)
  subcategories.include?(subcat) # probably better to match against ids
end

this method will return true if a specific category record has the passed-in subcategory.

inside your SubcategoriesHelper add the following method:

def category_class(cat, subcat)
  cat.has_child?(subcat) ? 'active' : '' 
end

this will return "active" if has_child? is true

Now you can use this category_class helper method inside the subcategories#show view when iterating through Category records:

...
<% @categories.each do |cat| %>
  <li class="<%= category_class(cat, @subcategory) %>">
    <%= cat.title %>
  </li>
<% end %>
...

Upvotes: 1

Related Questions