title: How do I optimize this sort by has_many relation count
body: <p>This works, but something tells me I really should do it in SQL.<br>
  Which I'm really bad at, so please help me.</p>
  
  <p>I want to sort my <code>user</code>s by their amount of <code>gesture</code>s in the current or a specified month.</p>
  
  <p>I have this in <code>User.rb</code>:</p>
  
  <pre><code>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 &lt;=&gt;
      a.gestures.done_in_month(month, year).count }.first
  end
  </code></pre>
  
  <p>and this in <code>gesture.rb</code>:</p>
  
  <pre><code>scope :done_in_month, lambda { |*args|
    return nil if !args[0]
    date = Date.new((args[1] || Date.today.year), args[0])
    where(:done_on =&gt; date.beginning_of_month..date.end_of_month)
  }
  </code></pre>
  
  <p>Any help or guiding is greatly appreciated!</p>