0

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.

4

2 回答 2

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

所以:

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

但是,在这种情况下,由于您总共要测试三个可能的值,因此在switch辅助方法中的语句可能是最好的。

# 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>
于 2012-09-10T19:22:14.843 回答
0

你可以做

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

或者

<%= 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> %>

三元运算符通过将 if 语句替换为condition ? condition_true : condition_false

于 2012-09-10T19:29:54.197 回答