mahu mahu - 7 months ago 6
Ruby Question

Ruby format DateTimeParameter in where query

I want to do a query like this:

bookings = Booking.where(user_id: @current_user.id, start_at: date.to_datetime)


The problem in this case is, that I just get results in bookings which match a timestamp
00:00:00
which is quite logical.

Is there a possibility to format the
start_at
parameter in the query to date, so that I just compare two dates and not datetimes?

Answer

Try convert your datetime field to date via SQL:

bookings = Booking.where(user_id: @current_user.id)
                  .where("DATE(start_at) = ?", date)

DATE() extracts the date part of a datetime expression.

Note: it does not works in PotsgreSQL

Or:

bookings = Booking.where(user_id: @current_user.id,
                         created_at: date.beginning_of_day..date.end_of_day)