Rails 5活动记录查询,其中日期范围与其他日期范围重叠

Sea*_*ley 2 activerecord datetime ruby-on-rails

我有一个模型与planting_date_beginplanting_date_end.我想检索所有planting_date_begin..planting_date_end与日期重叠的日期的记录current_week

例如:如果planting_date_begin:3/5/2017和planting_date_end:2017年3月12日,本周是2017年3月26日2017年1月1日,它不包含在查询中.

如果planting_date_begin:3/1/2017和:2017年planting_date_end4月15日它将包括在内.

我设置current_week范围:

today = Date.today
days_in_week = today.at_beginning_of_week..today.at_end_of_week
Run Code Online (Sandbox Code Playgroud)

这种语法不对,但我想做的事情如下:

Planting.where((planting_date_begin..planting_date_end).overlaps?(days_in_week) )
Run Code Online (Sandbox Code Playgroud)

处理这个问题的简洁方法是什么?顺便说一下,我正在使用postgres,以防有不同的方法.

Ste*_*zyn 5

也许不是很简洁,但我必须在当前的项目中做很多事情,我的方法是...

start_date = Date.today.at_beginning_of_week
end_date = Date.today.at_end_of_week

@plantings = Planting.where('planting_date_end >= ? AND planting_date_begin <= ?', start_date, end_date)
Run Code Online (Sandbox Code Playgroud)

这包括所有重叠..如果种植在范围之前开始并在范围之后结束,如果在范围内开始种植,如果种植在范围内结束.