Nick Ginanto
Nick Ginanto

Reputation: 32130

Conditionals inside the link_to description in rails

I have a link_to messages

<%= link_to "Messages (#{Messages.count})", messages_path %>

but if the count is 0 I'd like to remove the (0).

How do I incorporate this 'If condition' inside the link_to?

Upvotes: 1

Views: 428

Answers (1)

tadman
tadman

Reputation: 211590

You have a few options, but this one should work in this case:

link_to "Messages #{Messages.count > 0 ? '(%d)' : ''}" % Messages.count, messages_path

For more sophisticated logic than this you'd want to make a helper method:

link_to label_with_optional_counter("Messages", Messages.count), messages_path

You define that method in the appropriate helper module:

def label_with_optional_counter(label, count)
  "%s #{count > 0 ? '(%d)' : ''}" % [ label, count ]
end

Upvotes: 3

Related Questions