Ruby在where查询中格式化DateTime参数

Ruby format DateTimeParameter in where query

我想做这样的查询:

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

这种情况下的问题是,我只得到与时间戳 00:00:00 匹配的预订结果,这很合乎逻辑。

是否可以将查询中的 start_at 参数格式化为日期,以便我只比较两个日期而不是日期时间?

尝试通过 SQL:

将您的日期时间字段转换为日期
bookings = Booking.where(user_id: @current_user.id)
                  .where("DATE(start_at) = ?", date)

DATE() 提取日期时间表达式的日期部分。

注意:它在 Potsgre 中不起作用SQL

或者:

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

这个怎么样?

bookings = Booking.where(user_id: @current_user.id, start_at: start_date..end_date)

bookings = Booking.where(user_id: @current_user.id)
                  .where('start_at > ? AND start_at < ?', start_date, end_date)

其中 start_date 和 end_date 是您要检查的两个日期。