Domanda

Im creating an app using RoR to manage a basketball league. I have two tables: Teams & Games. The Games table takes two teams using foreign keys and contains the amount scored by each team like so:

Teams and Games

Now, I would like to list all the teams, followed by their win-loss record. I cannot think of an easier way of doing this rather than a foreach loop that counts all the records in the games table that contains the team, and the team has more than the other team. And then again for losses. There has to be an easier way.

Any suggestions?

È stato utile?

Soluzione

I agree that it would be best to stay away from loading all the records and counting these in Ruby. Doing it in a SQL query will be much faster.

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top