Rails Group by inside Group by

时间:2017-07-13 16:00:22

标签: sql ruby-on-rails ruby group-by activemodel

我需要首先将我的ActiveRecords分组为YEAR,然后再按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:我使用Ruby 2.3和Rails 4.2

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

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

不知道是否有更有效的方式(或更简洁),但认为这是有效的。试一试!

答案 2 :(得分:0)

你可以试试这个

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