gpt4 book ai didi

ruby-on-rails - Ruby 遍历日期

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:53 24 4
gpt4 key购买 nike

你好,我有这样的 Schedules 表;

<ActiveRecord::Relation [#<Schedule id: 427, date: "2016-06-15", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 428, date: "2016-06-16", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 429, date: "2016-06-17", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 430, date: "2016-06-22", notes: "", price: "253", promo: "", status: "available", boat_id: 3, created_at: "2016-06-14 09:23:55", updated_at: "2016-06-14 09:23:55">, #<Schedule id: 431, date: "2016-06-23", notes: "", price: "253", promo: "", status: "available", boat_id: 3, created_at: "2016-06-14 09:23:55", updated_at: "2016-06-14 09:23:55">]

和用户输入“从”和“到”日期。假设我有这样的变量

a = "2016-06-16".in_time_zone('UTC')
b = "2016-06-19".in_time_zone('UTC')

我想在这些日期(a 和 b)之间循环 Schedule 表并获得价格总和..

我想到了一个这样的解决方案,我可以说;

a = "2016-06-16".in_time_zone('UTC')
b = "2016-06-19".in_time_zone('UTC')
schedules = Schedule.all
price = 0

dates = []
while a < b do
dates << a
a += 1.day
end

然后;

dates.each do |date|
schedules.each do |schedule|
if (date == schedule.in_time_zone('UTC'))
price += schedule.price.to_i
end
end
end

但不知道这是否是最方便的方法。

最佳答案

为什么不利用 DB native 实现。您可以在 SQL 中完成。

date_from = "2016-06-16".in_time_zone('UTC')
date_to = "2016-06-19".in_time_zone('UTC')

Schedule
.where(date: date_from..date_to) # sql BETWEEN operator
.sum("price") # SQL aggregate function.

关于ruby-on-rails - Ruby 遍历日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com