Summing Related Tables Using Active Record

How to sum all the "summary" columns in an association?

My SQL-fu sucks, so I would like to learn how to do it using Active Record for my rails 2.3.5 application (so I haven’t liked any fashionable syntax ;-) And I'm in MySQL.

Let's say I have:


Shop 

has_many :customers
has_many :transactions, :through => :customers

So, normal stuff.


shop = Shop.first
shop.transactions
=> 100 

Ok, all this background for the question:

I want the SUM column totalin transactions for the last year (January 1, 2010..Dec 31 2010) and display them by the client.

As long as I know how to group transactions and find with conditions, this is the amount that SQL is missing me.


first = Date.new(2010, 01, 01)
last = Date.new(2010, 12, 31)

shop.transactions(:conditions => {:created_at => first..last}, :group => :customer_id, :include => sum(:total))

I just took a hit, am I on the right track?

+3
source share
2 answers

shop.transactions.sum(:total, :conditions => {:created_at => first..last}, :group => :customer_id)

. , AR. .

+8

.

, :

transactions = Shop.transactions
total = 0
sum = transactions.collect{|i| total+=i.transaction.amount}

, .

.sum

sum = transactions.to_a.sum(&:amount) 
0

Source: https://habr.com/ru/post/1782841/


All Articles