复杂的日期查找和注入

发布于 2024-08-14 05:42:34 字数 771 浏览 9 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

杀お生予夺 2024-08-21 05:42:34

此语句可能会执行您想要的操作:

financial_statements_ytd.inject(0) {|sum, statement| sum + statement.revenue }

This statement may do what you want:

financial_statements_ytd.inject(0) {|sum, statement| sum + statement.revenue }
二货你真萌 2024-08-21 05:42:34

您还可以查看 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.

浅语花开 2024-08-21 05:42:34

financial_statement 对象中保存您想要的值的字段名称是什么?
假设字段名称为ammount,则只需将inject语句修改为:

financial_statements_ytd.inject {|sum, revenue| sum + revenue.ammount }

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 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文