【问题标题】:Display string if null value in db如果数据库中的值为空,则显示字符串
【发布时间】:2011-12-21 12:10:45
【问题描述】:

我有下表,其中显示了匹配结果以及登录用户的匹配选择。当在数据库中找不到相关记录但我不确定如何执行此操作时,我想在 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 %>

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 在某些情况下重载模型中的访问器会更好,因此您不必在要显示“默认”值的每个视图中重复此逻辑。
    • 我已经尝试了上面的代码 sn-p 但它似乎没有工作,因为列显示为空白
    【解决方案2】:

    您可以将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 %>
    

    我在每一行都添加了&lt;%%&gt;,因为我认为它更清晰。不过,您可以只为每个代码块使用一个,例如:

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

    我不确定您对特定灯具有多少用户选择,但这会找到所有这些,所以如果有负载,您会得到所有这些,这将导致性能不佳和表中出现大量行。不过你比我更了解你的数据,也许用户选择有限制。

    【讨论】:

    • 嘿 Shadwell 非常感谢您的帮助,这解决了我的问题 :) 我打算每个游戏周每个用户只有 1 个选择,所以这应该不是问题,尽管感谢您的提醒 :-)
    猜你喜欢
    • 1970-01-01
    • 2013-05-27
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2018-09-02
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多