0

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?

1 Answer 1

2

Personally, I would do this in SQL - SUM(quantity) and GROUP BY outcome_id.

If you want it in Ruby, you can do

holdings = Holding.find_all_by_user_id(21)

sums = Hash.new(0)

holdings.each do |h|
  sums[h.outcome_id] += h.quantity
end

sums is 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.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree doing it in SQL is the better solution. It returns a lot less data which is always helpful, plus the DBM is made for that sort of lifting. The only time I'd retrieve the entire row is if I have to do subsequent processing of the data based on the sums.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.