问题描述
我有一个交易表,需要查找日期与今天日期匹配的记录.
I have a table of deals and need to find records where the date matches today's date.
从 rails 控制台,我需要匹配的日期字段看起来像这样.我已经分配了一个记录来处理测试.
From the rails console, the date field I need to match looks like this. I've assigned a record to deal for testing.
ruby-1.9.2-p0 > deal.start
=> Tue, 10 May 2011 00:00:00 UTC +00:00
如果我尝试像这样查找与今天开始日期匹配的任何记录,我会得到零
If I try to find any records matching the start date with today like this I get nil
ruby-1.9.2-p0 > Deal.find_by_start(Date.today)
=> nil
然后我想我可以通过将 Date.today 转换为日期时间来匹配.
then I thought I could match by converting Date.today to a datetime.
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.
How can I get this to work? I'm using Rails 3.
我想过将它们都转换为一致的格式,这将起作用,但在尝试使用 find_by_start 方法时不起作用
I thought about converting them both to a consistent format which will works but not when trying to using the find_by_start method
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 包含日期和时间,因此您正在寻找具有精确值的记录,而不仅仅是同一天.
Keep in mind a DateTime holds a date and a time, so you're looking for records that have a precise value, not just the same day.
您可以通过以下两种方式之一执行此操作.您可以选择从一天开始到结束的时间范围,也可以创建一个 date
列以帮助更好地对数据进行分组.
You can do this one of two ways. You can either select the range of time from the beginning of the day to the end, or you can create a date
column to help group your data better.
范围版本如下所示:
@deals = Deal.where('start BETWEEN ? AND ?', DateTime.now.beginning_of_day, DateTime.now.end_of_day).all
另一个需要在您的表中创建一个新的 start_date
列,并相应地用日期填充它.您可以将此日期编入索引并让您的查询运行得更快,因为在大型数据集上选择范围并不总是很快.
The other one requires creating a new start_date
column in your table and populating it with the dates accordingly. You can index this date and have your queries run much faster, as range selections aren't always quick on large sets of data.
这篇关于查找日期时间与今天日期匹配的记录 - Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!