轨道 按内部分组 分组依据



我需要先按年份,然后按月份对我的活动记录进行分组,如下所示:

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

谢谢

PS:我的模型中有名为"年"和"月"的列。

PS2:我使用 Ruby 2.3 和 Rails 4.2

.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]

你可以做嵌套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

不知道是否有更有效(或不那么冗长(的方法可以做到这一点,但认为这有效。试一试!

你可以试试这个

Model.all.inject({}) do |hash, record|
hash[record.year] = Hash.new { |h, k| h[k] = [] }
hash[record.year][record.month] << project
hash
end

最新更新