我有一个像这样创建的对象数组:
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)
但我不想再进行数据库查询。那么,最好的方法是什么?
最佳答案
您可以将查询链接在一起:
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
关于ruby-on-rails - 检查日期是否在日期范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25913604/