问题
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