2011-02-10 6 views
1

これは動作しますが、実際にSQLで行うべきことがあります。
私は本当に悪いので、私を助けてください。このソートをhas_manyリレーション数で最適化するには

userを現在の月または指定した月のgesture秒でソートしたいと考えています。

私はUser.rbでこれを持っている:

gesture.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 

と、この:

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

使用この

 
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" 
+0

。ありがとうございました。 – mikker

関連する問題