Reputation: 10350
Our app has a lease_booking model with a field of lease_date which is a datatime (we use sqlite for development and mysql for production). The app needs to find all the lease_booking on a given date. The code is like:
LeaseBooking.where("lease_date == ?", '2012-1-5')
The problem is that we can not find any lease_booking on 2012/1/5 because the lease_date is a date+time format. How can the app compare the date part only for a datatime field in rails 3.1?
thanks.
Upvotes: 3
Views: 2318
Reputation: 1314
Alternately, try this:
scope :booking_date, lamda {|d| where('lease_date > ?', Date.parse(d).to_time).where('lease_date < ?', (Date.parse(d) +1).to_time)}
And just call
LeaseBooking.booking_date('2012-01-05')
The where
-chaining is ugly, but whether or not you can use multiple ?
placeholders, or named variables, to do it in one statement, is highly DB-dependent. ARel is pretty good at turning even ugly chained queries into efficient SQL, though.
Upvotes: 3
Reputation: 2746
I'm afraid you'd have to do :
LeaseBooking.where("date(lease_date) = ?", '2012-1-5')
(with only one =
sign)
Maybe there is a better answer, because call the "date" function is not really pretty for ActiveRecord! Like Jason Lewis says in the comments, it is DB-specific.
Upvotes: 5