Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby on rails parameter compare date with datetime?

I receive this parameter: param[:date] = '2017-03-04'

and the column in my database is created_at with this format: '2017-01-01 09:21:23'

When I execute this query

Mymodel.where(created_at: params[:date]) 

It returns an empty array, and it is logic due the time that is not passed

I need all the rows that corresponds to the param date.

How can I do this? The time is not important in this case, I only need the date.
I am using postgres as db.

I need to select e.g. All Sell of a specific day and the column to search is created_at.

like image 289
matQ Avatar asked Oct 28 '25 07:10

matQ


1 Answers

This is a type-coercion problem. Because the created_at field contains a date and time, your date is being converted into 2017-03-04 00:00:00 for the query. Anything that doesn't exactly match that timestamp will be excluded.

There are two approaches to solving this problem.

Database agnostic

Turn your date into a Range object. ActiveSupport provides the Date#all_day helper for this use-case.

date = Date.parse(params[:date])

MyModel.where(created_at: date.all_day)

Since Date::parse throws an exception if parsing fails, the real-world implementation would have to account for that

my_models = begin
  date = Date.parse(params[:date])

  MyModel.where(created_at: date.all_day)
rescue ArgumentError
  MyModel.all
end

Postgres

You can cast your created_at field to date so that only the date part will be matched.

MyModel.where("created_at::date = ?", params[:date])
like image 150
Adam Lassek Avatar answered Oct 31 '25 00:10

Adam Lassek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!