Hilmi Yamcı
Hilmi Yamcı

Reputation: 473

Ruby aggregate function with model

I have a product model in my ruby on rails application which has name,endorsement and expense attributes.

I need to write a query that list all records, but for every record I need to calculate endorsement-expense as income value. That seems to be ok. However, I need to sum all of the incomes consequtively as well.

For example my records are like these:


Name Endorsement Expense
X    100         25
Y    20          17
X    60          55  
T    178         78

I need to list those values as:


Name Endorsement Expense Income  Total Income
X    100         25      75      75
Y    20          17      3       78
X    60          55      5       83 
T    178         78      100     183

How can I do that ?

Thanks.

Upvotes: 2

Views: 873

Answers (3)

Mikhail Katrin
Mikhail Katrin

Reputation: 2384

You can apply inject function to accumulate total income.

It will look something like this:

products.inject{|sum, product| sum += (product.endorsement - product.expense }

Upvotes: 0

satlosb
satlosb

Reputation: 42

You can also do it with a total income for each product:

products = Product.select("(endorsement - expense) AS 'income', name, endorsement, created_at, null as total") 
products.each do |p|
   p.total = Product.select("sum(endorsement) - sum(expense) AS 'total'").where(name: p.name).where("created_at <= ?", p.created_at).group('name').last.total
end

Upvotes: 0

a131
a131

Reputation: 564

rows = Product.select('name,endorsement,expense, (endorsement-expense) as income')

total_income = 0
rows.each do |row|
  total_income += row.income
  puts "#{row.name}, #{row.endorsement}, #{row.expense}, #{row.income}, #{total_income}"
end

Upvotes: 1

Related Questions