你好,我有这样的 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
但不知道这是否是最方便的方法。
我是一名优秀的程序员,十分优秀!