FranGoitia
FranGoitia

Reputation: 2003

Can't find record by Date [Rails 4]

I'm having the problem that I can't find records by searching in a datetime attribute. I have a flight model that has a datetime attribute called date. From a form I'm getting a value in the format %d/%m/%Y and I'm proceeding to execute a query using that information, but it always returns en empty ActiveRelation.

Some things I've tried:

Flight.first.date == params[:date] 
#=> true 

Date.parse(params[:date]) == Flight.first.date 
#=>true

Flight.where(date: params[:date])
  CACHE (0.0ms)  SELECT "flights".* FROM "flights" WHERE "flights"."date" = ?  [["date", "30/03/2015"]]
#<ActiveRecord::Relation []>
Flight.where(date: Date.parse(params[:date]))
  CACHE (0.0ms)  SELECT "flights".* FROM "flights" WHERE "flights"."date" = '2015-03-30'
#<ActiveRecord::Relation []>


#params[:date] is equal to "30/03/2015"

First.flight.date #is equal to Mon, 30 Mar 2015 00:00:00 UTC +00:00

Any help would really be appreciated. Thanks.

Upvotes: 1

Views: 179

Answers (2)

archit gupta
archit gupta

Reputation: 1034

Try this

Flight.where(["date like ?", "%#{Date.parse(params[:date])}%"])

Or

Flight.where(["date like ?", "%#{params[:date].to_date}%"])

Upvotes: 0

mgrim
mgrim

Reputation: 1302

You'll want to compare flights to a date range

parsed_datetime = DateTime.parse(params[:date])
Flight.where(date: (parsed_datetime)..(parsed_datetime + 1.day))

See https://stackoverflow.com/a/13700805/4640187

Upvotes: 3

Related Questions