Frage

Currently I have in my view something like this:

<table>
<tr>
   <% if item.status == nil %>
       <td><%= image_tag "/assets/nil.gif" %></td>
   <% else %>
       <% if item.status == "1" %>
           <td><%= image_tag "/assets/yes.gif" %></td>
       <% else %>
           <td><%= image_tag "/assets/no.gif" %></td>
       <% end %>
   <% end %>
</tr>
...

Can I use a ternary operator here? I didn't know where to put the ? or the : when using this combination of embedded ruby and html.

War es hilfreich?

Lösung

<%= 1 == 1 ? "one is one" : "one is two" %>
# outputs "one is one"

Therefore:

<%= image_tag "/assests/#{ item.status == "1" ? "yes" : "no"}.gif" %>

However, in this case, since you are testing three possible values in all, a switch statement inside a helper method might be best.

# app/helpers/items_help.rb

def gif_name(status)
  case status
  when nil
    "nil"
  when "1"
    "yes"
  else
    "no"
  end
end

# app/views/items/action.html.erb

<td><%= image_tag "/assests/#{gif_name(item.status)}.gif" %></td>

Andere Tipps

You could do

<%= item.status.nil? ? <td><%= image_tag "/assets/nil.gif" %></td> : <td><%= image_tag "/assets/#{item.status == '1' ? 'yes.gif' : 'no.gif'" %></td>

or

<%= item.status.nil? ? <td><%= image_tag "/assets/nil.gif" %></td> : item.status == "1" ? <td><%= image_tag "/assets/yes.gif" %></td> : <td><%= image_tag "/assets/no.gif" %></td> %>

The ternary operator substitutes the if statement by having the condition ? condition_true : condition_false

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top