通过has_many关联的总和对对象进行排序

时间:2010-08-12 22:56:50

标签: ruby-on-rails

我有两个对象:

class Person < ActiveRecord::Base
   has_many :tests
end

class Test <ActiveRecord::Base
   belongs_to :person
end

我需要通过测试中的分数总和来对所有人物对象进行排序。另一个技巧是每个人可能没有测试。

我已经通过我的测试得到了这个,但我无法根据该人的分数总和让他们订购,因为我无法弄清楚如何引用计算的值。

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

一旦我有了这个,我如何将其归还给要排序的球员列表?

1 个答案:

答案 0 :(得分:1)

老问题,但最近我试图找到类似问题的解决方案:

在rails 3中,它只是

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}")
相关问题