views:

32

answers:

3

I am building a financial reporting app with Ruby on Rails. In the app I have monthly financial statement objects (with 'revenue' as an attribute). For any single financial statement, I want show (1) year-to-date revenue, and (2) last-year-to-date revenue (calendar years are fine). Each object also has a Date (not Datetime) attribute called 'month' (watch out for 'month' variable name vs. 'month' method name confusion...maybe I should change that variable name).

So...

I think I need to (1) 'find' the array of financial statements (i.e., objects) in the appropriate date range, then (2) sum the 'revenue' fields. My code so far is...

def ytd_revenue
  # Get all financial_statements for year-to-date.
      financial_statements_ytd = self.company.financial_statements.find(:all, 
      :conditions => ["month BETWEEN ? and ?", "self.month.year AND month.month = 1",
      "self.month.year AND self.month.month" ])
  # Sum the 'revenue' attribute
      financial_statements_ytd.inject(0) {|sum, revenue| sum + revenue }

end

This does not break the app, but returns '0' which cannot be correct.

Any ideas or help would be appreciated!

A: 

What is the name of the field in financial_statement object that holds the value you want? Supposing that the field name is ammount then just modify the inject statement to be:

financial_statements_ytd.inject {|sum, revenue| sum + revenue.ammount }
khelll
+1  A: 

This statement may do what you want:

financial_statements_ytd.inject(0) {|sum, statement| sum + statement.revenue }
Jordan Miner
+1  A: 

You can also look into ActiveRecord's sum class method - you can pass in the field name and conditions to get the sum.

kejadlen