编写此日期范围范围是更好的方法吗?

时间:2013-09-13 10:35:46

标签: mysql ruby-on-rails ruby scope

我有选择班次的余地:

scope :by_date, lambda { |date|
  where "end_date BETWEEN ? AND ? OR start_date BETWEEN ? AND ?", date.beginning_of_day, date.end_of_day, date.beginning_of_day, date.end_of_day
}

更清洁的方法吗?

2 个答案:

答案 0 :(得分:2)

scope :by_date, lambda { |date| 
  where("DATE(start_date) = :date OR DATE(end_date) = :date", date: date.to_date) 
}

答案 1 :(得分:1)

这个怎么样:

scope :by_date, lambda { |date|
  where("end_date BETWEEN :beginning AND :end OR start_date BETWEEN :beginning AND :end",
    beginning: date.beginning_of_day, end: date.end_of_day)
}