ActiveRecord多个日期范围

时间:2017-04-19 14:16:55

标签: ruby-on-rails ruby activerecord

是否有更多的ActiveRecord惯用方法可以找到哪个记录在某个date_range中有start_atend_at? (基本上,需要找到在给定时间范围内开始或结束的记录)。这就是我目前正在做的事情:

Project.where('(start_at >= ? AND start_at <= ?) OR (end_at >= ? AND end_at <= ?)', start_at, end_at, start_at, end_at)

2 个答案:

答案 0 :(得分:6)

您可以将ranges传递给where并使用or

time_range = (start_at..end_at)
Project.where(start_at: time_range).or(Project.where(end_at: time_range))

答案 1 :(得分:1)

对于Rails 4,您可以使用BETWEENhash参数:

Project.where(
  "(start_at BETWEEN :start_at AND :end_at) OR (end_at BETWEEN :start_at AND :end_at)",
  start_at: start_at.beginning_of_day, end_at: end_at.end_of_day)