2012-04-29 72 views
1

我正在使用RoR創建一個應用程序來管理一個籃球聯賽。我有兩個表格:Teams & Games。該Games表需要使用外鍵兩隊包含每個隊打進像這樣的量:使用遊戲桌獲得隊伍桌中每支球隊的雙贏?

Teams and Games

現在,我想列出所有的球隊,其次是他們的輸贏記錄。我想不出一個更簡單的方法來做這件事,而不是一個foreach循環來計算包含團隊的遊戲表中的所有記錄,而團隊比其他團隊多。然後又是虧損。必須有一個更簡單的方法。

有什麼建議嗎?

回答

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 
+0

愛它,我不知道爲什麼我沒有想到這一點。保持發佈,我必須爲每個遊戲的每位玩家添加統計信息! –

+0

祝你好運:)我編輯了幾次,所以確保你看到了最新版本。 –