Ruby-on-rails 如何在rails活动记录中的日期指定小于今天的条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8457902/
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
How to specify a less than today condition on a date in rails active record
提问by Adam
I'm trying to figure out how to pull all the records in my set where their fields "publish" is true and "expires" is less than today. I have the following but i dont think the less than part is working, can someone please point me on the right track?
我试图弄清楚如何在我的集合中提取所有记录,其中他们的字段“发布”为真,“过期”少于今天。我有以下内容,但我不认为少于部分有效,有人可以指出我的正确方向吗?
@announcements = Announcement.where(:publish => true, :expires < Date.today)
Thanks in advance for your help
在此先感谢您的帮助
回答by leonardoborges
Try this:
尝试这个:
@announcements = Announcement.where("publish = ? AND expires < ?", true, Date.today)
回答by wycleffsean
Since this comes up first on google I thought I'd chime in. It's probably better to rely on Arel in this circumstance.
由于这首先出现在 google 上,我想我会插话。在这种情况下,最好依靠 Arel。
expires = Announcement.arel_table[:expires]
@announcements = Announcement.where(:publish => true)
.where(expires.lt(Date.today))
That will build the following SQL query
这将构建以下 SQL 查询
-- Using Arel
SELECT "announcements".* FROM "announcements"
WHERE "announcements"."publish" = 't'
AND ("announcements"."expires" < '2016-02-03 18:41:26.454325')
-- Contrast that with the string binding method mentioned above
SELECT "announcements".* FROM "announcements"
WHERE (publish = 't' AND expires < '2016-02-03 18:41:26.454325')
The column names are fully qualified, so you will avoid conflicts when composing other queries on top of this ActiveRecord::Relation i.e @announcements
列名是完全限定的,因此在此 ActiveRecord::Relation 之上编写其他查询时将避免冲突,即 @announcements

