2011-12-21 129 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

相關問題