I am trying to execute an ActiveRecord query in Rails 3.1, where I sort the results in a subcategory of grouped items, in this case grouped by date.
I think my code can explain this best. This is my method that works, but issues 4 requests to get the job done. It does not seem very effective for this.
def entry_days days = @user.entry_groups.find( :all, :select => 'date', :limit => 3, :group => 'date').map(&:date) entry_days = days.map do |date| { :date => date, :entry_groups => @user.entry_groups.find_all_by_date(date) } end end
Using the Dave Newton sentence below to use group_by, I rewrote the method as follows:
def entry_days dates_with_entries = @user.entry_groups.find( :all, :select => 'date', :limit => 3, :group => 'date').map(&:date) @user.entry_groups.where(:date => dates_with_entries).all.group_by(&:date). map do |date, entry_groups| { :date => date, :entry_groups => entry_groups } end end
At least I have only 2 queries left.
Then I wrote the method again as follows:
dates_with_entries = user.entry_groups.all( :select => 'date', :limit => num_days, :order => 'date DESC', :group => 'date').map(&:date) entry_groups = user.entry_groups. where( :date => dates_with_entries ). all(:order => 'date DESC') entry_days = entry_days.group_by(&:date). map { |date, entry_groups| { :date => date, :entry_groups => entry_groups } }
On the side of the note: Should I not bind so many methods together, and what is the preferred indentation format for nested methods and hashes?