获得比赛的胜利者 - rails 方式?
Getting the winner of a match - the rails way?
在我的(联赛)视图中,我想列出所有比赛并将比赛标记为已进行、获胜球队或比赛为平局。
要知道是平局还是谁是赢家,我必须检查每个对手的分数。我在哪里进行这些计算?查看助手?模型范围?
我的想法是在列出匹配项时使用三个函数来检查每个匹配项:
match.played? -> 真/假
match.tie? -> 真/假
match.winner? -> 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 |
....
你绝对是在正确的道路上。我会采用您在我的 Match
模型中建议的方法,但有一个例外:
match.winner #=> returns the Team object of the winner (or nil).
然后我会有一个视图助手调用这些方法来确定如何呈现它们。即,播放过吗?是领带吗?谁赢了。
你的问题范围有点宽泛,无法给出明确的答案;)
问 5 个开发者,你会得到 12 个不同的答案。
话虽如此,这就是我要做的:
你实现这些实例方法的想法是一个很好的起点,虽然我个人不喜欢“?”不 return 布尔值的方法,在我看来它应该只是 #winner
并且应该 return 团队实例,而不是 id(我认为有一个 "Team" 模型)。您可能需要考虑一种互补的 #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
并在您的视图助手中执行此操作(return "not yet played" 或其他)。
在我的(联赛)视图中,我想列出所有比赛并将比赛标记为已进行、获胜球队或比赛为平局。
要知道是平局还是谁是赢家,我必须检查每个对手的分数。我在哪里进行这些计算?查看助手?模型范围?
我的想法是在列出匹配项时使用三个函数来检查每个匹配项:
match.played? -> 真/假
match.tie? -> 真/假
match.winner? -> 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 |
....
你绝对是在正确的道路上。我会采用您在我的 Match
模型中建议的方法,但有一个例外:
match.winner #=> returns the Team object of the winner (or nil).
然后我会有一个视图助手调用这些方法来确定如何呈现它们。即,播放过吗?是领带吗?谁赢了。
你的问题范围有点宽泛,无法给出明确的答案;) 问 5 个开发者,你会得到 12 个不同的答案。
话虽如此,这就是我要做的:
你实现这些实例方法的想法是一个很好的起点,虽然我个人不喜欢“?”不 return 布尔值的方法,在我看来它应该只是 #winner
并且应该 return 团队实例,而不是 id(我认为有一个 "Team" 模型)。您可能需要考虑一种互补的 #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
并在您的视图助手中执行此操作(return "not yet played" 或其他)。