0

I have a sidebar that holds a list of posts. I need the corresponding post on my sidebar to have an active class. What i have currently does not work so what is the best way to do this?

def is_active?(path)
  current_page?(path) ? "active" : ""
end

<% @posts.each do |post| %>  
    <%= link_to post.title, post, class: is_active?(posts_path) %>  
<% end %>
EliteViper7777
  • 187
  • 1
  • 12

2 Answers2

0

As I said in my comment, methods ending by ? should return a boolean value. If you decide to go against the convention this will make things harder for us.

I suggest you actually use an active_link_to like it is explained in that question.

However the main problem was that you didn't generate the URL properly for each post :

is_active?(posts_path)

The posts_path is the path to the index and not the individual post resource. You should use something like post_path(post)

You want to do something like this :

First your is_active? method, because it has a ? should return a boolean

def is_active?(path)
  current_page?(path)
end

Then you can use it this way (you need to get the URL of the post using the post_path(post) helper)

<% @posts.each do |post| %>  
    <%= link_to post.title, post, class: ('active' if is_active?(post_path(post))) %>  
<% end %>

EDIT : because is_active? does the same thing as current_page? you should simply replace the is_active? code by an alias declaration

alias :is_active? current_page? 
Community
  • 1
  • 1
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164
0

I had to develop such a solution some years before. I implemented the following as helper methods to detect an active link. Be aware that this is not the best solution I think. I had to provide a full url. Fell free to edit the code to use a path or a parameter hash instead.

# Returns true or false if the page is displayed that belongs to the given url.
def link_selected?(url)
  request_method = request.method.to_sym
  begin
    url_params = Revolution::Application.routes.recognize_path(
      url, {:method=>request_method}
    )
  rescue Exception => e
    {}
  end
  begin
    request_params = Revolution::Application.routes.recognize_path(
      request.url, {:method=>request_method}
    )
  rescue
    {}
  end  
  return true if url_params == request_params
  return false
end

def is_active?(url)
  return link_selected?(url) ? 'active' : nil
end
guitarman
  • 3,290
  • 1
  • 17
  • 27