Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislerum/3337e8f84a3251785565555197330be2 to your computer and use it in GitHub Desktop.
Save chrislerum/3337e8f84a3251785565555197330be2 to your computer and use it in GitHub Desktop.
5 def self.top_player
6 averages = {}
7 joins(:games).group(:id).each {|player| averages[player.name.to_sym] = player.games.average(:score).to_i}
8 averages.max_by{|k,v| v}[0]
9 end
irb(main):019:0> Player.joins(:games).group(:id).select('*, AVG(games.score) AS average_score')
Player Load (0.3ms) SELECT *, AVG(games.score) AS average_score FROM "players" INNER JOIN "games" ON "games"."player_id" = "players"."id" GROUP BY "players"."id"
[
[0] #<Player:0x007f8c94ec8e20> {
:id => 4,
:name => "asdffd",
:created_at => Mon, 13 Jun 2016 16:13:41 UTC +00:00,
:updated_at => Mon, 13 Jun 2016 16:13:41 UTC +00:00
},
[1] #<Player:0x007f8c94ec8b28> {
:id => 6,
:name => "fsdfdsf",
:created_at => Mon, 13 Jun 2016 16:14:27 UTC +00:00,
:updated_at => Mon, 13 Jun 2016 16:14:27 UTC +00:00
},
[2] #<Player:0x007f8c94ec8808> {
:id => 8,
:name => "fdsfasdf",
:created_at => Mon, 13 Jun 2016 16:14:48 UTC +00:00,
:updated_at => Mon, 13 Jun 2016 16:14:48 UTC +00:00
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment