Ruby-on-rails Rails ActiveRecord 查询日期范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20413456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails ActiveRecord Query Date Range
提问by Cody Barr
I'm trying to use the following line in my controller to capture all tasks due less than a week from the current date:
我试图在我的控制器中使用以下行来捕获距当前日期不到一周的所有任务:
@due_this_week = current_user.tasks.where(due_date: Date.today..1.week.from_now)
For some reason it's not finding any results even I know I have tasks due within four and six days. This is the only instance variable using a range query. I have another one that works fine to find overdue tasks:
出于某种原因,它没有找到任何结果,即使我知道我有四六天内到期的任务。这是使用范围查询的唯一实例变量。我还有一个可以很好地找到过期任务的方法:
@overdue = current_user.tasks.where("due_date <= ?", Date.today)
What am I missing?
我错过了什么?
采纳答案by Cody Barr
Turns out my controller somehow wasn't set up correctly and was no longer saving the current_user's ID when creating new assignments, which is why they weren't being found. I figured this out using the rails console and running a find on the last few assignments submitted. The user_idwas set to nil. Thanks for the assist @mu is too short.
结果我的控制器不知何故没有正确设置,并且current_user在创建新分配时不再保存的 ID,这就是为什么没有找到它们的原因。我使用 rails 控制台解决了这个问题,并对提交的最后几个作业进行了查找。将user_id被设置为nil。感谢您的帮助@mu 太短了。
回答by NARKOZ
Should be:
应该:
@due_this_week = current_user.tasks.where(due_date: 1.week.ago..Date.today)

