我正在使用RoR创建一个应用来管理篮球联赛。我有两张桌子:Teams
& Games
。 Games
表使用外键占用两个团队,并包含每个团队得分的数量,如下所示:
现在,我想列出所有球队,然后是他们的输赢记录。我不能想到一个更简单的方法,而不是一个foreach循环,它计算包含团队的游戏表中的所有记录,并且团队比其他团队更多。然后又是亏损。必须有一个更简单的方法。
有什么建议吗?
答案 0 :(得分:0)
我同意最好不要加载所有记录并在Ruby中计算这些记录。在SQL查询中执行它会快得多。
def team_stats(team_id)
# Wins are any game where the team played and scored higher than the other team
wins = Game.where('(home_team_id = ? AND home_team_score > away_team_score) OR (away_team_id = ? AND home_team_score < away_team_score)', team_id, team_id).count
# The opposite for losses
losses = Game.where('(home_team_id = ? AND home_team_score < away_team_score) OR (away_team_id = ? AND home_team_score > away_team_score)', team_id, team_id).count
# Ties are not accounted for
return {:wins => wins, :losses => losses}
end