我想在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
}
}
在一個側面說明:我應該不會被鏈接這麼多的方法一起使用,以及什麼是嵌套的方法和哈希首選縮進格式?
This question:http://stackoverflow.com/questions/6953512/rails-3-1-with-postgresql-group-by-must-be-used-in-an-aggregate-function/6953704#6953704,討論類似的東西 – rubish