【问题标题】:Getting the winner of a match - the rails way?获得比赛的获胜者 - 轨道方式?
【发布时间】:2016-10-13 15:06:48
【问题描述】:

在我的(联赛)视图中,我想列出所有比赛并将比赛标记为已进行、获胜球队或比赛为平局。

要知道是平局还是赢家,我必须检查每个对手的得分。我在哪里进行这些计算?查看助手?,模型范围?

我的想法是在列出匹配项时使用三个函数来检查每个匹配项:
比赛。玩过? -> 真/假
比赛。领带? -> 真/假
比赛获胜者? -> 得分最高的team_id。

数据库(postgresql)

匹配

id | league_id | date
---+-----------+----------
1  | 1         | 2016-03-21 21:00:00
2  | 1         | 2016-03-22 09:00:00
...

对手 (未播放则为空)

id | match_id | team_id | score
---+----------+---------+--------
1  |  1       |  1      |  0
2  |  1       |  2      |  1
3  |  2       |  3      |  1
4  |  2       |  4      |  1
4  |  3       |  1      |  
4  |  3       |  2      |  
....

【问题讨论】:

    标签: ruby-on-rails postgresql ruby-on-rails-4 postgresql-9.5


    【解决方案1】:

    您绝对是在正确的道路上。我会在我的Match 模型上使用您建议的方法,但有一个例外:

    match.winner #=> returns the Team object of the winner (or nil).
    

    然后我会有一个视图助手,它调用这些方法来确定如何呈现它们。即,它被播放了吗?是领带吗?谁赢了。

    【讨论】:

      【解决方案2】:

      您的问题范围有点宽泛,无法给出明确的答案;) 问 5 位开发者,你会得到 12 个不同的答案。

      也就是说,这就是我要做的: 您实现这些实例方法的想法是一个很好的起点,尽管我个人不喜欢“?”不返回布尔值的方法,在我看来,它应该只是 #winner 并且应该返回团队实例,而不是 id(我认为它有一个“团队”模型)。您可能需要考虑一个补充的 #loser 方法。

      您的视图可能如下所示:

      <table>
        <% @matches.each_with_index do |match, i| %>
        <tr>
          <td class="match number">
            <%= i + 1 %>
          </td>
          <td class="team-1">
            <%= match.team_1 %>
          </td>
          <td class="team-2">
            <%= match.team_2 %>
          </td>
          <td class="winner">
            <% if match.played? %>
              <!-- this would be a view helper since you have to consider
                   the tie situation and we do not want that much logic
                   in the view. It would return a string with either the
                   teams name or "tie". -->
              <%= winner_of_match match %>
            <% else %>
              N/A
            <% end %>
          </td>
          <!-- etc... -->
        </tr>
        <% end %>
      </table>
      

      这只是为您提供构建想法的非常基本的方法。例如,您可能想要摆脱 if match.played 并在您的视图助手中执行此操作(返回“尚未播放”或其他内容)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-02
        • 1970-01-01
        • 2021-08-04
        • 2012-05-20
        • 1970-01-01
        • 1970-01-01
        • 2013-03-08
        • 1970-01-01
        相关资源
        最近更新 更多