如何在rails活动记录中的日期上指定小于今天的条件

时间:2011-12-10 16:15:47

标签: ruby-on-rails activerecord if-statement

我正在试图找出如何拉取我的集合中的所有记录,其中“发布”字段为真,“过期”小于今天。我有以下但我不认为不到一部分工作,有人可以指出我在正确的轨道上?

  @announcements = Announcement.where(:publish => true, :expires < Date.today)

提前感谢您的帮助

2 个答案:

答案 0 :(得分:50)

试试这个:

@announcements = Announcement.where("publish = ? AND expires < ?", true, Date.today)

答案 1 :(得分:25)

由于这首先出现在Google上,我以为我会加入进来。在这种情况下依赖Arel可能会更好。

expires = Announcement.arel_table[:expires]
@announcements = Announcement.where(:publish => true)
  .where(expires.lt(Date.today))

这将构建以下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')

列名是完全限定的,因此在ActiveRecord :: Relation之上编写其他查询时会避免冲突,即@announcements