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
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
Try this:
@announcements = Announcement.where("publish = ? AND expires < ?", true, Date.today)