Fianite Fianite - 11 months ago 58
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:


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 Source

I think the following should do it:

  .order('SUM(player_stats.goals) DESC')

You can use scope in your case:

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

and in controller: