Rails按第一列分组,然后按第二列分组

时间:2016-04-03 18:03:40

标签: ruby-on-rails ruby postgresql ruby-on-rails-4 group-by

我的团队模型有两个属性,.type.sub type

我想先通过team.type然后team.subtype打电话给他们。

我试过

  Team.all.group_by{|e| [e.type, e.sub_type]}

但这让我感动

{
  ["Sport", "Football"] => [
                            teamObject,
                            teamObject
                           ],
  ["Sport", "Soccer"] => [
                            teamObject,
                            teamObject
                           ],
}

我想要的是......

{
 "Sport" => {
              "Football" => [ 
                              teamObject, 
                              teamObject
                            ],
              "Soccer" => [
                             teamObject,
                             teamObject
                            ],
            },
 "Drama" => {
              "Band" => [ teamObject, teamObject],
              "Dance" => [ teamObject, teamObject],
            },        
}

我的查询或过滤器应该是什么样的?理想情况下,我想把它变成一个范围。

注意:我不想创建更多模型,表格或关系。

1 个答案:

答案 0 :(得分:1)

我会尝试这样的事情:

Team.all.
     group_by { |e| e.type }.
     map { |k, v| [k, v.group_by { |e| e.sub_type }].to_h }

或者:

Hash.new { |h, k| h[k] = Hash.new { |h, k| h[k] = [] } }.tap do |hash|
  Team.all.each { |t| hash[t.type][t.sub_type] << t }
end