简体   繁体   English

在Rails的.where()中比较日期时间和日期

[英]Comparing datetime and date in a .where() on Rails

I'm working on an event system where admins can select events to feature and add promotional text. 我正在使用一个事件系统,管理员可以在其中选择要显示的事件并添加促销文字。 As they need to add additional text the featured events are in their own table and reference the event details. 由于他们需要添加其他文本,因此特色事件位于其自己的表中,并引用事件详细信息。

I'm now trying to output featured events for each day in the next week. 我现在正尝试输出下周每一天的特色活动。 Simplified example: 简化示例:

day = DateTime.now.to_date
featured_events = @featured_events.where('event.start_datetime = ?', day)

The problem is that start_datetime is in datetime format and day is in date format so it always outputs nothing. 问题在于start_datetime为日期时间格式,而day为日期格式,因此它始终不输出任何内容。 Is it possible to compare these two values with .where() ? 是否可以使用.where()比较这两个值?

Thanks! 谢谢!

You don't say what database you're using. 您没有说您正在使用什么数据库。

In PostgreSQL we'd truncate the datetime inside the DB query so the DBM can do the compare. 在PostgreSQL中,我们将截断数据库查询中的日期时间 ,以便DBM可以进行比较。 On MySQL we'd use a function to convert the datetime to a date . 在MySQL上,我们将使用一个函数将datetime转换为date

可能是您在寻找这个:

@featured_events.where('event.start_datetime > ? and event.start_datetime < ?', DateTime.now, 1.day.from_now.beginning_of_day)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM