Zavius
Zavius

Reputation: 11

Ordering objects by a sum of has_many association

I have two objects:

class Person < ActiveRecord::Base
   has_many :tests
end

class Test <ActiveRecord::Base
   belongs_to :person
end

I need to sort all my person objects by the sum of scores on the test. One other trick is each person may not have a test.

I've gotten as far as this with my tests but I can't get them to order based on the sum of the scores for that person because I can't figure out how to reference the value being calculated.

Score.sum(:score, :group => :person_id)

Once I have this how do I get this back to a list of players to sort?

Upvotes: 1

Views: 1109

Answers (1)

santuxus
santuxus

Reputation: 3702

Old question, but recently I was trying to find a solution to similar problem:

in rails 3, it's just

class Person < ActiveRecord::Base
  has_many :tests
  scope :order_by_score, lambda {|direction| joins(:tests).group(:person_id).order("sum(score) #{direction}")
end
# when Person also has attribute 'score', it should be .order("sum('tests.score') #{direction}")

Upvotes: 1

Related Questions