我将ScheduleDay模型作为;
=> #<ActiveRecord::Relation [#<ScheduleDay id: 1, from: "2017-01-21 00:00:00", to: "2017-01-30 00:00:00", weekday: 100, weekend: 200, weekly: 90, available: true, check_in: "09:00", check_out: "18:00", min_stay: 2, sevendays: false, check_in_day: nil, created_at: "2017-01-14 11:25:18", updated_at: "2017-01-14 11:27:00">, #<ScheduleDay id: 2, from: "2017-02-05 00:00:00", to: "2017-02-15 00:00:00", weekday: 150, weekend: 200, weekly: 140, available: nil, check_in: "09:00", check_out: "18:00", min_stay: 3, sevendays: false, check_in_day: nil, created_at: "2017-01-14 15:53:21", updated_at: "2017-01-14 15:54:43">, #<ScheduleDay id: 3, from: "2017-03-15 00:00:00", to: "2017-06-15 00:00:00", weekday: nil, weekend: nil, weekly: nil, available: false, check_in: nil, check_out: nil, min_stay: 1, sevendays: false, check_in_day: nil, created_at: "2017-01-14 15:56:01", updated_at: "2017-01-14 15:56:57">, #<ScheduleDay id: 4, from: "2017-08-05 00:00:00", to: "2017-09-30 00:00:00", weekday: 500, weekend: 500, weekly: 500, available: true, check_in: "09:00", check_out: "18:00", min_stay: 7, sevendays: true, check_in_day: "Saturday", boat_id: nil, created_at: "2017-01-14 16:01:00", updated_at: "2017-01-14 16:02:10">]>
我有另一个日期范围,我想在ScheduleDay表中循环我的日期范围,如果找到记录,则获取一些数据。如果没有找到,那么也获取数据。我尝试了不同的方式,但我正在寻找红宝石中最有效的方法。
first = Date.parse("05.2.2017")
last = (Date.parse("16.2.2017"))
schedules = ScheduleDay.where(from: Date.today..(last+1.day))
dates = []
(first..last).each do |date|
flag = 0
catch :date_found do
schedules.each do |s|
(s.from.to_date..s.to.to_date).each do |d|
puts date
puts d
if date == d
flag += 1
puts 'found'
throw :date_found
end
end
end
if flag == 0
puts 'date not found'
end
end
end
这是我到目前为止所尝试的。但问题是,如果找不到,我无法访问记录。如果我采取;
if flag == 0
puts 'date not found'
end
在schedules.each...
循环内,然后为ScheduleDay中的每条记录打印未找到。我想循环遍历所有ScheduleDay记录,如果没有找到,则获取一些数据。
修改
我有用户保存的数据库记录。用户可以通过选择日期范围和定价来自定义一年中的任何日期。我也问用户群定价。
所以,假设用户输入了15.01.2017&amp; 21.01.2017自定义价格:100和基本价格200(如果在数据库日期范围内找不到日期,将使用基本价格)。
我想返回二月份的json数组。所以我需要;
01.01.2017 -> custom price exists? if not get base price
02.01.2017 -> custom price exists? if not get base price
...
15.01.2017 -> yes! custom price exists get custom price
16.01.2017 -> yes! custom price exists get custom price
17.01.2017 -> yes! custom price exists get custom price
18.01.2017 -> yes! custom price exists get custom price
...
21.01.2017 -> yes! custom price exists get custom price
...
31.01.2017 -> custom price exists? if not get base price
然后创建json
EDIT2
如果我使用该怎么办;
first = Date.parse("05.2.2017")
last = Date.parse("16.2.2017")
(first..last).each do |date|
schedules.each do |s|
d2 = (s.from.to_date..s.to.to_date)
puts d2 === date
puts d2
puts date
end
end
===
检查日期是否在范围内。