Getting 'active_link_to' to work properly with Pagination
I am trying to get active_link_to to work properly when I use pagination. I have 3 nav-tabs and they all work fine when selected, however, when I click on my pagination button to view more records my current nav-tab losses it's active status (style). What steps do I need to fix this issue?
Also 1 more minor issue if somebody doesn't mind. I'm using a log-in screen to get me to my main layout. When I log in, none of the nav-tabs are active. How do I render this? If I click on one of them it shows active but I want the 1st tab to display active by default. Again, I am using active_link_to.
Here is my updated post with Code:
In my Gemfile I have
gem kaminari gem active_link_to
In my projects_controller.rb
@projects = Kaminari.paginate_array(@projects).page(params[:page]).per(10)
In my index.html.erb
At the end of my page
<%= paginate @projects %>
In my projects_helper.rb
def active_link_to(text, link) content_tag(:li, :class => request.fullpath == link ? 'active' :nil) do link_to text, link end end
In my Layout application.html.erb
<ul class="nav nav-tabs"> <li><%= active_link_to("Active Projects", projects_path) %></li> .... .... </ul>
The problem is you are trying to match the link to the fullpath entirely and your fullpath will sometimes contain a query string which will break the fullpath == link if you don't also include the query string in your link.
One possible solution would be to match a substring of the fullpath, something like this:
def active_link_to(text, link) content_tag(:li, :class => request.fullpath.starts_with?(link) ? 'active' :nil) do link_to text, link end end
Or even using Ruby String's  method to ask if a substring is present in the string:
def active_link_to(text, link) content_tag(:li, :class => request.fullpath[link].present? ? 'active' :nil) do link_to text, link end end
You can also try a Gem that provides the method you want: https://github.com/comfy/active_link_to
It uses a more comprehensive method of matching paths.