简体   繁体   English

Rails:按子模型中的统计数据总和订购模型?

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

I have a Player model, a Player model has many PlayerStats.我有一个 Player 模型,一个 Player 模型有很多 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?如何使用 Player 模型来检索控制器中进球最多的球员列表?

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.但我不能这样做,因为玩家没有直接目标,它有许多包含他们目标的 PlayerStats。

NOTE: I'm using a mySQL database.注意:我使用的是 mySQL 数据库。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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