我搜索过类似的问题,但我发现的与我想要达到的完全不同。
我试图获取给定日期的状态,该状态将在数据库中的开始日期和结束日期之间的天数范围内。
记录:
#<Schedule id: 1, starts_at: "2015-10-03", ends_at: "2015-10-15", status: "Available">
#<Schedule id: 2, starts_at: "2015-10-16", ends_at: "2015-10-30", status: "Busy">
检索日期状态的最佳方式是什么?&#34; 2015-10-9&#34;?
答案 0 :(得分:1)
考虑到您的schedule.starts_at
和schedule.ends_at
是格式化的日期:
date = Date.new(2015, 10, 9)
# matching_date is going to return us the schedules where the date is matched
matching_dates = schedule.select{|schedule| schedule.starts_at < date && schedule.ends_at > date}
# now, the map method is going to return us the status for every given matching_dates
statuses = matching_dates.map(&:status)
请注意,我对matching_dates
和statuses
说了多个,因为select
方法会返回一个包含所有匹配日期的数组。
我们可以(并且应该,我猜:))通过在我们的时间表上设置where
条款来做到这一点,这可能更好,但在我看来不太明确。无论哪种方式,我们都会得到一系列匹配日期。