如何通过has_many关系计数优化此排序

时间:2011-02-10 10:24:28

标签: ruby-on-rails activerecord

这很有效,但有些东西告诉我,我真的应该在SQL中这样做 我真的很擅长,所以请帮助我。

我希望按当前或指定月份user的{​​{1}}次数对gesture进行排序。

我在User.rb

中有这个
def self.mayor(month = nil, year = nil)
  month = Date.today.month if !month
  year = Date.today.year if !year
  self.all.sort { |a, b|
    b.gestures.done_in_month(month, year).count <=>
    a.gestures.done_in_month(month, year).count }.first
end

,这在gesture.rb

scope :done_in_month, lambda { |*args|
  return nil if !args[0]
  date = Date.new((args[1] || Date.today.year), args[0])
  where(:done_on => date.beginning_of_month..date.end_of_month)
}

非常感谢任何帮助或指导!

1 个答案:

答案 0 :(得分:1)

使用此

def self.mayors(month = Date.today.month, year = Date.today.year)
  date = Date.new(year, month)
  self.group("users.id").
    joins(:gestures).
    select("users.*, COUNT(users.id) as gestures_count").
    order("gestures_count DESC").
    where(:gestures => {:done_on => date.beginning_of_month..date.end_of_month})
end

def self.mayor(month = Date.today.month, year = Date.today.year)
  self.mayors(month, year).first
end

喜欢:

User.mayors(1,2011).map(&:gestures_count)
#=> [20, 15, 15, 12, 3]

mayor = User.mayor
puts "Our mayor user is: " + mayor.name + ", with " + mayour.gestures_count + " gestures"