Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group Rails query into arrays by attribute

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 }
  ] },
]
like image 650
gberger Avatar asked Sep 18 '13 01:09

gberger


2 Answers

Got it!

People.all.group_by(&:age)
like image 122
gberger Avatar answered Oct 21 '22 01:10

gberger


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.

like image 32
agmin Avatar answered Oct 21 '22 01:10

agmin