How to sort results based on join table in Rails?

女生的网名这么多〃 提交于 2019-12-24 01:18:37

问题


I have Account model,

class Account < ActiveRecord::Base
  has_many :account_games
  def score
    account_games.map(&:score).sum
  end
end

And AccountGame :

class AccountGame < ActiveRecord::Base
  belongs_to :account
end

What is the best way to get accounts with the highest score? as you can see, score is the summation of related account_games score field.

Thanks


回答1:


try

Account.joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score')

which will give you a hash where the keys are the account_ids and the values are the total score.

You can pass a limit option to accounts to get the top x accounts. something like

Account.limit(10).joins(:account_games).sum('account_games.score', group: :account_id, order: 'sum_account_games_score DESC')


来源:https://stackoverflow.com/questions/14997289/how-to-sort-results-based-on-join-table-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!