Is it possible to return a hash with named keys from an ActiveRecord group query?

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 }, ...

      

+3


source to share


2 answers


You can return ActiveRecord :: Relation with a single request.



Purchase.select("user_id as id, sum(price) as price").group("user_id")

      

+3


source


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.

0


source







All Articles