How can I group by two columns and provide the sum of grouped items

I am creating an inventory database and it has 2 columns that I would like to group (by manufacturer and model). How can I group these columns and provide the sum of a group of elements?

For example:

Qty Manufacturer Model 1 Sony MF-2002 1 Sony MF-2002 1 Planar PL2410W 1 Planar PL2410W 1 Planar PL2410W 1 Planar PL3610D 1 Planar PL3610D 

Result:

 Qty Manufacturer Model 2 Sony MF-2002 3 Planar PL2410W 2 Planar PL3610D 
+7
source share
1 answer

Assuming the Item model, you can pass an array to the group method as follows:

 Item.group(["manufacturer", "model"]).sum(:qty) # => {["Planar", "PL2410W"]=>3, ["Planar", "PL3610D"]=>2, ["Sony", "MF-2002"]=>2} 
+9
source

All Articles