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

前端 未结 2 1166
独厮守ぢ
独厮守ぢ 2021-02-02 06:49

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

相关标签:
2条回答
  • 2021-02-02 07:29

    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

    0 讨论(0)
  • 2021-02-02 07:37

    Try this:

    @announcements = Announcement.where("publish = ? AND expires < ?", true, Date.today)
    
    0 讨论(0)
提交回复
热议问题