Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Find with Date

I'm having a hard time figuring this out but how do I tell my finder statement to ignore the time of the Datetime field in the db?

def trips_leaving_in_two_weeks
  Trip.find(:all, :conditions => ["depart_date = ?", 2.weeks.from_now.to_date])
end

I want depart_date to come back as just a date but it keeps returning the time as well and causing this equality not to work. Is there someway to just compare against the dates? Thanks

Edit

Here's the code I'm using now that works:

Trip.find(:all, :conditions => ["DATE(depart_date) = ?", 2.weeks.from_now.to_date])
like image 438
CalebHC Avatar asked Jan 28 '11 21:01

CalebHC


2 Answers

Not sure which DB you're using but does this work?

"depart_date = DATE(?)"
like image 101
Peter Brown Avatar answered Oct 13 '22 22:10

Peter Brown


I would use this approach:

Rails 3.x

Trip.where(
  :depart_date => 2.weeks.from_now.beginning_of_day..2.weeks.from_now.end_of_day
)

Rails 2.x

Trip.all(
:conditions => {
  :depart_date => 2.weeks.from_now.beginning_of_day..2.weeks.from_now.end_of_day
})

If you index the depart_date column this solution will be efficient as the query uses the index. This solution is DB neutral.

When calculated fields are used in a where clause, the performance degrades(unless there is a special index).

like image 4
Harish Shetty Avatar answered Oct 13 '22 22:10

Harish Shetty