我的团队模型有两个属性,.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],
},
}
我的查询或过滤器应该是什么样的?理想情况下,我想把它变成一个范围。
注意:我不想创建更多模型,表格或关系。
答案 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