【问题标题】:Retrieve record where a date is between start and end dates检索日期在开始日期和结束日期之间的记录
【发布时间】:2015-10-03 13:06:06
【问题描述】:

我已经搜索过类似的问题,但我发现的与我想要实现的完全不同。

我正在尝试获取给定日期的状态,该状态将在数据库中的开始日期和结束日期之间的天数范围内。

记录:

#<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">

检索日期为“2015-10-9”的日期状态的最佳方法是什么?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    考虑到您的schedule.starts_atschedule.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_datesstatuses,因为 select 方法会返回一个包含所有匹配日期的数组。

    我们可以(并且应该,我猜 :) )通过在我们的日程表上添加一个where 子句来做到这一点,这可能会更好,但在我看来不太明确。无论哪种方式,我们都会得到匹配日期的集合。

    【讨论】:

    • 是的,那是我的问题,我一直在尝试使用where 子句,但是嘿,我喜欢这个解决方案,完美。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多