Rails Group by inside 分组依据

Rails Group by inside Group by

我需要先按 YEAR 对 ActiveRecords 进行分组,然后按 MONTH 进行分组,如下所示:

{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:我的模型中有名为 YEAR 和 MONTH 的列。

PS2:我用的是Ruby2.3和Rails4.2

您可以嵌套 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
.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]