开发者

Add a selected class to links depending on id

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!


Beware: params are always strings.

So :

 controller.params[:id].to_i == portfolio.id

SideNote: extract this kind of logic in helpers, it's much cleaner.


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:

def class_for_porfolio_entry(portfolio)
  controller.class == PortfoliosController and
    controller.action_name == 'show' and
    controller.params[:id].to_i == portfolio.id ?
      'selected' :
      ''
end

You've got a whole lot going on there, so you might want to look at ways of reducing the complexity, for instance using params instead:

def class_for_porfolio_entry(portfolio)
  params[:controller] == 'portfolios' and
    params[:action] == 'show' and
    params[:id].to_i == portfolio.id ?
      'selected' :
      ''
end

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:

def class_for_porfolio_entry(portfolio)
  if (@show_selected_portfolio and @portfolio.id == portfolio.id)
    'selected'
  else
    ''
  end
end

This presumes you have an instance variable @portfolio, which is usually the case in any controller's show method, and that you will set @show_selected_portfolio to true in any controller method where this logic applies.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜