1

I'm using rails to try and calculate the total of a specific column in my database. I'm using this at the moment:

@total = Product.sum (:cost)

Which works and returns the combined cost of everything in the table. What about if I'm trying to do that from data which is already in an array? For example:

@products = Product.where('date >= ? AND date <= ?', Date.today.beginning_of_month.to_datetime, Date.today.end_of_month.end_of_day.to_datetime)

Can you then do the same thing on that array of products?

Hope someone can help! Ta.

0

2 Answers 2

4

You can simply append .sum to the resulting ActiveRecord object:

Product.where('date >= ? AND date <= ?',
 Date.today.beginning_of_month.to_datetime,
 Date.today.end_of_month.end_of_day.to_datetime).sum(:cost)

This will produce a query similar to

select sum(cost) from products where (date >= ... and date <= ...)
Sign up to request clarification or add additional context in comments.

1 Comment

Oh fantastic! Can you then add this to it's own partial? Hope that's the correct terminology?
2

If you already have an instantiated array (not a relation object), you can use inject:

@total = @products.collect(&:cost).inject {|sum, cost| sum += cost }

meagar's answer works better if you have the relation though.

Comments

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.