Rails的ActiveRecord的团体成绩为子集按日期 [英] Rails ActiveRecord group results into sub-collections by date
问题描述
我想要做的Rails 3.1的ActiveRecord的查询我的排序结果为子集分组的项目,在这种情况下,按日期进行分组。
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.
我觉得我的code最能解释它。这是我的方法,它的作品,但发出4查询完成这项工作。它似乎并不十分有效地做这种方式。
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.
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,我已经重新编写的方法是这样的:
Using the suggestion from Dave Newton below to use group_by, I have re-written the method like this:
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查询。
At least I have it down to only 2 queries now.
然后我又重新写了这样的方法:
Then I re-wrote the method again like this:
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
}
}
在一个侧面说明:我应该不会链接这么多的方法在一起,什么是preferred缩进格式嵌套方法和散列
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?
推荐答案
为什么不选择全部,然后使用类似的 GROUP_BY ?
Why not select them all then use something like group_by?
这篇关于Rails的ActiveRecord的团体成绩为子集按日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!