10

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 }
  ] },
]
gberger
  • 2,605
  • 2
  • 22
  • 48

2 Answers2

25

Got it!

People.all.group_by(&:age)
gberger
  • 2,605
  • 2
  • 22
  • 48
9

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.

de-russification
  • 31,008
  • 6
  • 34
  • 52
agmin
  • 8,288
  • 2
  • 18
  • 26
  • I like the one with the block! Unfortunately I named an association the same way as a column in my PG view and Rails was trying to do some "unexpected" magic with that. Luckily I was able to do akin to `people.group_by{|p| p.read_attribute(:age) }`. – mlt Jan 23 '20 at 19:27