检查日期是否在日期范围内

时间:2014-09-18 13:11:06

标签: ruby-on-rails ruby date activerecord range

我有一个像这样创建的对象数组:

all_project_assignments = ProjectAssignment.where(active: true, hour_type_id: 1)

现在我想使用此结果数组仅选择日期范围内的分配。日期范围是:

date_range = @current_month.at_beginning_of_month..@current_month.at_end_of_month

all_project_assignments的每个成员都有必须在范围内的字段entry_date。

我的替代方案是:

project_assignments = ProjectAssignment.where(active: true, hour_type_id: 1, entry_date: date_range)

但我不想要另一个db查询。那么,最好的方法是什么?

3 个答案:

答案 0 :(得分:2)

您可以将查询链接在一起:

all_project_assignments = ProjectAssignment.where(active: true, hour_type_id: 1)
date_range = @current_month.at_beginning_of_month..@current_month.at_end_of_month
project_assignments = all_project_assignments.where(entry_date: date_range)

但是,这将再次查询数据库。

如果您想过滤检索到的行,只需执行

即可
project_assignments = all_project_assignments.select do |assignment|
    assignment.entry_date.between?(@current_month.at_beginning_of_month, @current_month.at_end_of_month)
end

答案 1 :(得分:1)

检查范围条件Rails guides

Client.where(created_at: (Time.now.midnight - 1.day)..Time.now.midnight)

这将产生以下SQL:

SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')

所以在你的情况下:

all_project_assignments = ProjectAssignment.where(active: true, hour_type_id: 1, entry_date: @current_month.at_beginning_of_month..@current_month.at_end_of_month)

请注意,如果您按当前月份(1..12)进行比较,您将获得同月的结果,但是来自去年。

答案 2 :(得分:0)

如果范围只是整个月,那么您可以尝试使用此查询吗?

project_assignments = all_project_assignments.select do |assignment|
    assignment.entry_date.month == @current_month
end

如果@current_month是整数

,则可能