I have an array of objects that looks like this:
[#<Holding id: 5, user_id: 21, outcome_id: 7, quantity: 200, cost_basis: nil, created_at: "2011-12-15 20:52:05", updated_at: "2011-12-15 20:52:05">,
#<Holding id: 6, user_id: 21, outcome_id: 7, quantity: 750, cost_basis: nil, created_at: "2011-12-15 21:31:30", updated_at: "2011-12-15 21:31:30">,
#<Holding id: 7, user_id: 21, outcome_id: 9, quantity: 1231, cost_basis: nil, created_at: "2011-12-15 21:35:31", updated_at: "2011-12-15 21:35:31">]
I retrieved this by using my model’s find_all_by_user_id (Holding.find_all_by_user_id(21)). What I need, however, is an array of sums. So, for instance, what I’d like to get instead in this instance is:
[#<Holding id: 5, user_id: 21, outcome_id: 7, quantity: 950, cost_basis: nil, created_at: "2011-12-15 20:52:05", updated_at: "2011-12-15 20:52:05">,
#<Holding id: 7, user_id: 21, outcome_id: 9, quantity: 1231, cost_basis: nil, created_at: "2011-12-15 21:35:31", updated_at: "2011-12-15 21:35:31">]
What would make it even better is if I could pull from my Outcomes model the Outcome.description and have it in this second array along with the id. Do I just have to loop over and create sums where outcome_id’s match or is there a better way?
Personally, I would do this in SQL –
SUM(quantity)andGROUP BY outcome_id.If you want it in Ruby, you can do
sumsis now a hash with key being all the outcome_ids and the value being the total quantity.Please note that in both solutions (SQL and Ruby) you will lose the information in the other fields (holding_id, user_id, cost_basis, timestamps), which may not be what you want.