我需要先按年对ActiveRecords进行分组,然后按月进行分组,如下所示:
{2017=>
"January"=>
[Record1, record2, etc]
"February"=>
[Record1, record2, etc]
2016=>
"January"=>
[Record1, record2, etc]
"February"=>
[Record1, record2, etc]
}以此类推。
我试着用
.group_by( |a| [a.year, a.month] ) 但我能得到的最好的结果是:
{[2017, "January"]=>
[Record1, record2, etc]
[2017,"February"]=>
[Record1, record2, etc]
[2016, "January"]=>
[Record1, record2, etc]
[2016,"February"]=>
[Record1, record2, etc]
}谢谢
附言:我在我的模型中有名为年和月的列。
PS2:我使用Ruby2.3和Rails4.2
发布于 2017-07-14 02:05:06
.group_by(&:year).each_with_object({}) {|(k, v), h| h[k] = v.group_by(&:month) }会给你你想要的:
{ 2017 => {
"January" => [record1, record2, etc],
"February" => [record1, record2, etc]
},
2016 => {
...所以
results[2017]['January'] #=> [record1, record2, etc]发布于 2017-07-14 00:06:32
你可以做嵌套的group_by。类似于:
Model.group_by(:year) do |year, objects|
objects.group_by(&:month) do |month, objects|
//Do the actions you need for that objects
end
end我不知道是否有更有效的方法(或更少的冗长)来做这件事,但我认为这是可行的。试一试!
发布于 2017-07-14 00:29:23
你可以试试这个
Model.all.inject({}) do |hash, record|
hash[record.year] = Hash.new { |h, k| h[k] = [] }
hash[record.year][record.month] << project
hash
endhttps://stackoverflow.com/questions/45085832
复制相似问题