简体   繁体   中英

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.

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('players.id').order('SUM(player_stats.goals) DESC')
  }
end

and in controller:

Player.by_goals.limit(7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM