msaunders
msaunders

Reputation: 131

Sum of related data

I'm building a Rails expense tracker for myself. I simply have categories and expenses, and I want to display a sum of the total related expenses on the Categories index view.

Right now a Category has_many :expenses and an Expense belongs_to :category.

What's the best way to go about displaying a sum of the total related expenses on the category page on for instance the "Grocery" line while it's iterating through the list of categories?

I thought this would be a simple thing to find, but I've hit a bit of a wall.

Upvotes: 1

Views: 166

Answers (2)

Carson Cole
Carson Cole

Reputation: 4461

In your controller

Category.all.each do |category|
  total = 0
  category.expenses.each {|expense| total += expense }
  @category_expenses[expense.name] = total
end

Then iterate through @category_expenses in your view.

Upvotes: 0

Naren Sisodiya
Naren Sisodiya

Reputation: 7288

you can write a method for total expenses in your Category model like follow:

def total_expenses
  self.expenses.sum(:amount) # assuming amount is the column holding expenses amount
end

access it as

category = Category.find(id)
category.total_expenses 

hope this help :)

Upvotes: 3

Related Questions