如果db中为null值,则显示字符串

时间:2011-12-21 12:10:45

标签: ruby-on-rails if-statement html-table where-clause

我有下表,其中显示了匹配的结果以及已登录用户的匹配选择。我想在selection.winner和selection.value列中显示文本值,如果在数据库中找不到相关记录但我不确定如何执行此操作。我的代码如下:

<% Fixture.where(:weekno => @gameweek.number).each do |fixture| %> 
  <tr>
    <td width="10"><%= fixture.date.strftime("%d/%m/%Y")%></td>
        <td width="10"><%= fixture.date.strftime("%H:%M") %></td>
        <td width="80"><%= fixture.home_team %></td> 
        <td width="10">Vs.</td>
        <td width="80"><%= fixture.away_team %></td>
        <td width="10"><%= fixture.result %></td>
        <% Selection.where(:userid => current_user.id, :fixtureno => fixture.id).each do |selection| %>       
            <td width="10"><%= selection.winner %></td>       
            <td width="10"><%= selection.value %></td>  
        <% end %>   
  </tr>
<% end %>

2 个答案:

答案 0 :(得分:3)

如果数据库字段为零,是否要显示任何字符串? 如果是,你可以使用,

<%= selection.winner || 'string' %>
<%= selection.value || 'string' %>

答案 1 :(得分:1)

您可以将Selection查找的结果放入变量并对其进行测试:

<% user_selections = Selection.where(:userid => current_user.id, :fixtureno => fixture.id) %>
<% if user_selections.empty? %>
  <td>You have no selections for this match.</td>
<% else %>
  <% user_selections.each do |selection| %>
    <td width="10"><%= selection.winner %></td>       
    <td width="10"><%= selection.value %></td>  
  <% end %>
<% end %>

我在每一行都放了一个<%%>因为我觉得它更清楚了。您可以为每个代码块使用一个,例如:

<% else 
  user_selections.each do |selection| %>

我不确定你对特定灯具有多少用户选择,但是这样就可以找到所有这些,所以如果有负载,你将获得所有这些将导致性能不佳和表格中的大量行。你知道你的数据比我好,也许用户选择有限制。