假设我有这些行:(表示为JSON):
[
{ name: "Bob", age: 10 },
{ name: "Carl", age: 15 },
{ name: "Alice", age: 10 },
{ name: "Derek", age: 20 }
]
我如何在Rails中按age
分组?例如,我想要这样的东西:
[
{ age: 10, objects: [
{ name: "Bob", age: 10 },
{ name: "Alice", age: 10 }
] },
{ age: 15, objects: [
{ name: "Carl", age: 15 }
] },
{ age: 20, objects: [
{ name: "Derek", age: 20 }
] },
]
答案 0 :(得分:14)
知道了!
People.all.group_by(&:age)
答案 1 :(得分:5)
如果您实际上正在处理JSON:
people.group_by{|p| p['age'] }
如果您正在处理ActiveRecord模型:
People.group('id, age')
Here还有关于使用ActiveRecord进行分组的其他文档。