复杂的日期查找和注入
我正在使用 Ruby on Rails 构建一个财务报告应用程序。在应用程序中,我有每月财务报表对象(以“收入”作为属性)。对于任何单一财务报表,我希望显示 (1) 今年迄今的收入,以及 (2) 去年至今的收入(日历年即可)。每个对象还有一个名为“month”的 Date(不是 Datetime)属性(注意“month”变量名称与“month”方法名称混淆...也许我应该更改该变量名称)。
所以...
我认为我需要(1)在适当的日期范围内“查找”财务报表(即对象)数组,然后(2)对“收入”字段求和。到目前为止,我的代码是...
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
这不会破坏应用程序,但返回“0”,这是不正确的。
任何想法或帮助将不胜感激!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此语句可能会执行您想要的操作:
This statement may do what you want:
您还可以查看 ActiveRecord 的 sum 类方法 - 您可以传入字段名称和条件即可得到总和。
You can also look into ActiveRecord's sum class method - you can pass in the field name and conditions to get the sum.
financial_statement
对象中保存您想要的值的字段名称是什么?假设字段名称为
ammount
,则只需将inject
语句修改为: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 theinject
statement to be: