My question is very similar to this one : Changing Current Tab in Rails
I am trying to add a ‘selected’ class to my link regarding the id of my portfolios controller’s show action
Here is what I’ve tried:
<ul>
<% for portfolio in @portfolios %>
<li class="<%= controller.class == PortfoliosController and controller.action_name == 'show' and controller.params[:id] == portfolio.id ? 'selected' : '' %>"><%= link_to portfolio.name, portfolio %></li>
<% end %>
</ul>
But it seems that the following:
controller.params[:id] == portfolio.id
doesn’t match correctly and I don’t understand why..
Thanks for your help!
You might be comparing string and numerical values, which in Ruby are not considered equivalent. A conversion of one of or the other might help. In fact, if you roll this up in a helper method, it might make it a lot easier to follow:
You’ve got a whole lot going on there, so you might want to look at ways of reducing the complexity, for instance using
paramsinstead:This could be simplified further if you had a boolean flag set in your controller that is later used as required, avoiding hard-coding something like this:
This presumes you have an instance variable
@portfolio, which is usually the case in any controller’sshowmethod, and that you will set@show_selected_portfoliototruein any controller method where this logic applies.