我同意最好遠離加載所有記錄並在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
愛它,我不知道爲什麼我沒有想到這一點。保持發佈,我必須爲每個遊戲的每位玩家添加統計信息! –
祝你好運:)我編輯了幾次,所以確保你看到了最新版本。 –