Eki Eqbal
Eki Eqbal

Reputation: 6027

How to sort results based on join table in Rails?

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

Upvotes: 2

Views: 1673

Answers (1)

jvnill
jvnill

Reputation: 29599

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')

Upvotes: 1

Related Questions