Jonathan Clark
Jonathan Clark

Reputation: 20538

Searching with date only

I am building a Rails 4.1.4 web app and I want to search by a specific date. When I search for "2014-07-01" I find nothing but when I search for "2014-07-01 10:00:00" I do find because that is the exact date (with time) in the database.

This is my code:

@timereports = Timereport.where("reported_at = ?", Time.parse(params[:date]))

How can I match only the date and ignore the time part?

Upvotes: 0

Views: 36

Answers (1)

DiegoSalazar
DiegoSalazar

Reputation: 13521

Dates are tricky, you have to compare the right type. In one you're using a date and the other a datetime. If you only care to find records at a certain date and not a specific time you'll need to cast the db field to a date:

@timereports = Timereport.where("DATE(reported_at) = ?", Date.parse(params[:date]))

That says to convert the db field reported_at to a DATE (e.g. "2014-07-01") and to compare it to Date.parse(params[:date]) which is also now "2014-07-01".

Upvotes: 1

Related Questions