【问题标题】:How to iterate all records that are within the current year? Rails 4如何迭代当前年份内的所有记录?导轨 4
【发布时间】:2023-04-11 01:17:01
【问题描述】:

我需要迭代数据库中的所有记录并对列的值求和,但仅限于今年。

例如,他们会问:“将拥有用户 1 年的所有购买相加。”

我如何在 Rails 中做到这一点?导轨?有什么方法可以为我提供这个任务吗?

例如,像这样的:

current_user.purchases.each do |purchase|
  total_purchase += purchase.amount.to_i*purchase.product.price.to_f
end

对不起我的英语。

【问题讨论】:

  • Sum all the purchases that have a user for 1 year. 这听起来更像是您需要将一岁或以上用户的所有购买相加。
  • @toolz 仅一年。仅 2014 年有用户的所有购买。

标签: ruby-on-rails time ruby-on-rails-4


【解决方案1】:

如果购买是与用户的 has_many 关系,并且有适当的日期字段,则可以使用

total_purchase = 0
current_user.purchases.where('date_field > ?', Time.now.beginning_of_year).each do |purchase|
  total_purchase += purchase.amount.to_f * purchase.product.price.to_f
end

或者如果您想使用去年,您可以更改 where 子句:
where(date_field: 1.year.ago.beginning_of_year..Time.now.beginning_of_year)

如果productpurchasebelongs_to 关系,请考虑使用.includes(:product) 来限制您的数据库查询。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
相关资源
最近更新 更多