Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use group to select the id's of the grouped records in Rails?

Purchase.all.group( :user_id ).sum( :price )

This returns

[{ 1 : 234 }, { 2 : 345 }, ...

Is it possible to pull the Purchase ids?

For example, suppose the first group returned:

{ user_id : 1, price : 234, ids : [3,6,9] }
like image 240
B Seven Avatar asked Jul 14 '15 00:07

B Seven


1 Answers

Using postgresql, you can use array_agg:

Purchase.select('user_id, sum(price) as price, array_agg(id) as ids').group('user_id')
like image 50
AbM Avatar answered Oct 17 '22 00:10

AbM