我有一个带有类型列的表,我想按该类型对所有记录进行分组......
我知道我能做到:
MyTable.group(:type).count
然后我得到类似的东西:
{ "some-type" => 123, "another-type" => 456 }
但我不想得到计数,而是想要实际记录,如下:
{ "some-type" => <ActiveRecordRelation: [<id="1" type="some-type">, <id="60" type="some-type">...]>, "another-type" => <ActiveRecordRelation: [<id="99" type="another-type">...] }
基本上,我正在寻找一种方法:
MyTable.group(:type).each do |key, values|
# ... do stuff with values...
end
而不是必须这样做:
MyTable.uniq.pluck('type').each do |type|
values = MyTable.where(:type => type)
# ... do stuff with values
end