2011-09-05 69 views
6

我想在Rails 3.1中執行ActiveRecord查詢,在那裏我將結果排序爲分組項目的子集合,在這種情況下按日期分組。Rails ActiveRecord組按日期分組結果到子集合

我想我的代碼可以最好地解釋它。這是我的方法,它可以工作,但發出4個查詢來完成工作。這樣做似乎效率不高。

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 

使用從下面戴夫牛頓的建議,使用GROUP_BY,我已經重新編寫的方法是這樣的:

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 

至少我現在有它下降到只有2查詢。

然後我又重新寫的方法是這樣的:

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 
     } 
     } 

在一個側面說明:我應該不會被鏈接這麼多的方法一起使用,以及什麼是嵌套的方法和哈希首選縮進格式?

+0

This question:http://stackoverflow.com/questions/6953512/rails-3-1-with-postgresql-group-by-must-be-used-in-an-aggregate-function/6953704#6953704,討論類似的東西 – rubish

回答

6

爲什麼不選擇它們然後使用類似group_by的東西?

+1

最終這個集合將由成千上萬的行支持,我只想要最近3天的條目,並且這些日子每個應該至少有1個條目。如果我沒有弄錯,你的建議是拉下查詢的所有行。我可以做到這一點,但我想保持我描述的行爲。 –

+0

我想我可以使用group_by方法將日期映射到條目,然後執行第二次選擇。這將使查詢總數降至2. –

+0

如果每天至少有一個條目,似乎您可以根據日期範圍和組選擇一次檢索。 –