Add class inline if ... (in 1 line)

Danpe picture Danpe · Oct 2, 2012 · Viewed 17.3k times · Source

I want to add a class to a link_to only if a statement is true.

<%= link_to product.name, product, :class => "last" if product == @products.last %>

The problem that the IF statement affects the whole line and not just the :class part.

I know i can get it done with IF ELSE, but is it possible to do it in 1 line ?

Answer

Alcides Queiroz picture Alcides Queiroz · Oct 2, 2012
<%= link_to product.name, product, :class => (product == @products.last ? "last" : "")  %>