title: Rails ActiveRecord group results into sub-collections by date
body: <p>I'm trying to do an ActiveRecord query in Rails 3.1 where I sort the results into sub-collections of grouped items, in this case grouped by date.</p>
  
  <p>I think my code can explain it best. This is my method, which works but issues 4 queries to get the job done. It doesn't seem very efficient to do it this way.</p>
  
  <pre><code>def entry_days
    days = @user.entry_groups.find(
      :all,
      :select =&gt; 'date',
      :limit =&gt; 3,
      :group =&gt; 'date').map(&amp;:date)
  
    entry_days = days.map do |date|
      { :date =&gt;  date,
        :entry_groups =&gt; @user.entry_groups.find_all_by_date(date)
      }
    end      
  end
  </code></pre>
  
  <p>Using the suggestion from Dave Newton below to use group_by, I have re-written the method like this:</p>
  
  <pre><code>def entry_days
    dates_with_entries = @user.entry_groups.find(
      :all,
      :select =&gt; 'date',
      :limit =&gt; 3,
      :group =&gt; 'date').map(&amp;:date)
  
    @user.entry_groups.where(:date =&gt; dates_with_entries).all.group_by(&amp;:date).
      map do |date, entry_groups|
        { :date =&gt; date,
          :entry_groups =&gt; entry_groups }
      end
  end
  </code></pre>
  
  <p>At least I have it down to only 2 queries now.</p>
  
  <p>Then I re-wrote the method again like this:</p>
  
  <pre><code>  dates_with_entries = user.entry_groups.all(
        :select =&gt; 'date',
        :limit =&gt; num_days,
        :order =&gt; 'date DESC',
        :group =&gt; 'date').map(&amp;:date)
  
    entry_groups = user.entry_groups.
        where(
          :date =&gt; dates_with_entries
        ).
        all(:order =&gt; 'date DESC')
  
    entry_days = entry_days.group_by(&amp;:date).
        map { |date, entry_groups|
          {
            :date =&gt; date,
            :entry_groups =&gt; entry_groups
          }
        }
  </code></pre>
  
  <p>On a side note: Should I not be chaining so many methods together, and what is the preferred indentation format for nested methods and hashes?</p>