The following query works as expected:
Purchase.all.group( :user_id ).sum( :price )
It returns an array of hashes:
[{ 1 : 234 }, ...
Is there a way to return an array of hashes with keys ?
[{ id : 1, price : 234 }, ...
You can return ActiveRecord :: Relation with a single request.
Purchase.select("user_id as id, sum(price) as price").group("user_id")
I believe this will do:
Purchase.all.group(:user_id).sum(:price).map do |k, v| { id: k.keys.pop, price: k.values.pop } end
Although a little hacky, it works.