2011-12-21 92 views
3

我有下表,其中显示了匹配结果以及该匹配的登录用户选择。当数据库中没有相关记录时,我想在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 %> 

回答

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

我不知道你有多少用户选择具有特定夹具,但这会发现他们所有,所以如果有负载你会把他们全部拿走,这会导致表现不佳,并且会在你的桌子上出现一大堆。尽管你比我更了解你的数据,但用户选择也许有限制。

+0

嘿沙德韦尔非常感谢您的帮助这解决了我的问题:)我打算要每名用户游戏周期只有1个选择,以便这不应该是一个问题,但感谢的头up :-) – 2011-12-21 13:45:46

3

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

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

在某些情况下,您会更好地重载模型中的访问器,因此您不必在每个要显示“默认”值的视图中重复此逻辑。 – Pavling 2011-12-21 13:37:57

+0

我试过了上面的代码片段,但它似乎不工作,因为列显示空白 – 2011-12-21 14:09:33

相关问题