DollarChills
DollarChills

Reputation: 1086

Group then loop through both records

I have a sporting site that I need to create a team one vs team two results page. I'm having a problem with the index page when trying to display team one vs team two.

The data is structured as such in mysql.

matchId | teamId | Score
2001233 | 986754 |   4
2001233 | 100765 |   6

I'm grouping by matchId, but unsure of how to loop through to get both teams.

Controller

@match = Match.group(:matchId)

Upvotes: 0

Views: 143

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

@matches = Match.group(:matchId).inject([]) do |results, matches|
  teams = Match.where(matchId: matches.matchId)
  results << [matches.matchId, teams.first.teamId, teams.first.score, teams.last.teamId, teams.last.score]
  results
end

This will give you an array of arrays in the instance variable @matches, each element will look like...

[2001233, 986754, 4, 100765, 6]

Upvotes: 1

Related Questions