11

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,813
  • 3
  • 28
  • 50

2 Answers2

27

Got it!

People.all.group_by(&:age)
gberger
  • 2,813
  • 3
  • 28
  • 50
10

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.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
agmin
  • 8,948
  • 2
  • 21
  • 27
  • 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