使用与今天的日期匹配的日期时间查找记录 – Ruby on Rails
我有一个交易表,需要查找日期与今天的日期相符的记录。
在rails控制台中,我需要匹配的日期字段如下所示。 我已经分配了一份记录来处理测试。
ruby-1.9.2-p0 > deal.start => Tue, 10 May 2011 00:00:00 UTC +00:00
如果我尝试找到与今天的开始日期匹配的任何记录,就像这样我得到零
ruby-1.9.2-p0 > Deal.find_by_start(Date.today) => nil
那么我认为我可以通过将Date.today转换为日期时间来匹配。
ruby-1.9.2-p0 > Date.today.to_datetime => Tue, 10 May 2011 00:00:00 +0000 ruby-1.9.2-p0 > Deal.find_by_start(Date.today.to_datetime) => nil
我怎样才能让它发挥作用? 我正在使用Rails 3。
编辑:我考虑过将它们转换为一致的格式,但是在尝试使用find_by_start方法时不会
ruby-1.9.2-p0 > deal.start.strftime("%a, %e %B %Y") == Date.today.strftime("%a, %e %B %Y") => true ruby-1.9.2-p0 > Deal.find_by_start.strftime("%a, %e %B %Y") == Date.today.strftime("%a, %e %B %Y") NoMethodError: undefined method `strftime' for nil:NilClass
请记住,DateTime包含日期和时间,因此您正在查找具有精确值的记录,而不仅仅是同一天。
你可以用两种方法之一做到这一点。 您可以选择从一天开始到结束的时间范围,也可以创建date
列以帮助更好地分组数据。
范围版本如下所示:
@deals = Deal.where('start BETWEEN ? AND ?', DateTime.now.beginning_of_day, DateTime.now.end_of_day).all
另一个需要在表中创建一个新的start_date
列,并相应地填充日期。 您可以将此日期编入索引,并使查询运行得更快,因为范围选择在大型数据集上并不总是很快。
Rails 5.1引入了Date#all_day
helper,它返回给定日期的范围对象,因此您只需编写:
Deal.where(start: Date.today.all_day)
您还可以使用SQL DATE()
函数来实现目标,例如:
@deals = Deal.where('DATE(start) = ?', Date.today)
对于那些仍然在Rails 4上的人:
为了增加上面的not_a_patch的答案,我会使用:
Deal.where(start: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)
因为Time.zone
将使用UTC(这是您的日期时间字段的存储方式),而DateTime.now
则不会。
> DateTime.now => Fri, 08 Sep 2017 11:28:21 -0400 > Time.zone.now => Fri, 08 Sep 2017 15:29:53 UTC +00:00