Fianite Fianite - 2 months ago 13
MySQL Question

Rails: Order Model by sum of stats in child model?

I have a Player model, a Player model has many PlayerStats.

If I wanted to get a Player's total goals, I'd use:

@player.player_stats.sum(:goals)


How can I use the Player model to retrieve a list of the players with the most goals in the controller?

I was thinking something like:

@players = Player.order(:goals).limit(7)


but I can't do that because a Player doesn't have goals directly, it has many PlayerStats which contain their goals.

NOTE: I'm using a mySQL database.

Answer

I think the following should do it:

Player
  .joins(:player_stats)
  .group('player_stats.id')
  .order('SUM(player_stats.goals) DESC')
  .limit(7)

You can use scope in your case:

class Player
  scope :by_goals, lambda {
    joins(:player_stats).group('player_stats.id').order('SUM(player_stats.goals) DESC')
  }
end

and in controller:

Player.by_goals.limit(7)