CalebHC
CalebHC

Reputation: 5042

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])

Upvotes: 6

Views: 5059

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64373

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).

Upvotes: 4

Peter Brown
Peter Brown

Reputation: 51717

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

"depart_date = DATE(?)"

Upvotes: 7

Related Questions