How to specify a less than today condition on a date in rails active record

坚强是说给别人听的谎言 提交于 2019-12-20 10:18:08

问题


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


回答1:


Try this:

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



回答2:


Since this comes up first on google I thought I'd chime in. It's probably better to rely on Arel in this circumstance.

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

That will build the following SQL query

-- 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



来源:https://stackoverflow.com/questions/8457902/how-to-specify-a-less-than-today-condition-on-a-date-in-rails-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!