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