Suppose I have these rows: (represented as JSON):
[
{ name: "Bob", age: 10 },
{ name: "Carl", age: 15 },
{ name: "Alice", age: 10 },
{ name: "Derek", age: 20 }
]
How can I, in Rails, group these by age
? For example, I want something like this:
[
{ 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 }
] },
]
Got it!
People.all.group_by(&:age)
If you're actually dealing with JSON:
people.group_by{|p| p['age'] }
If you're dealing with ActiveRecord models:
People.group('id, age')
Here there's additional documentation on grouping with ActiveRecord.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With