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

前端 未结 2 1174
独厮守ぢ
独厮守ぢ 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

提交回复
热议问题