Ruby on Rails:查询日期等于另一个日期(忽略时间)

5

我正在尝试在我的模型上执行此查询,但我无法弄清楚。

  • An event has a date.
  • I have an array of date called "array_of_dates", I have built it from another model:

    array_of_dates = []
    user.each do |user|
       array_of_dates << user.birthday_date
    end
    
  • user.birthday_date is of course a datetime
我尝试过。
Event.where("date in (?)", array_of_dates)

然而,来自事件的日期也有一个设置的时间。我想忽略这里设置的时间,因为我只是寻找那一天。我尝试将user.birthday_date解析为另一种格式,但我不知道如何改变Event模型中“date”的格式。

感谢您的帮助!

2个回答

8
使用日期函数:date
# if user's birthday_date column is date
Event.where("date(date) in (?)", User.pluck(:birthday_date))

# if user's birthday_date column is timestamp
Event.where("date(date) in (?)", User.select("date(birthday_date)"))

非常感谢!是的,birthday_date 是一个时间戳(实际上它并不是生日日期,但这样解释更容易理解)。 - user4187589

1
首先,将 array_of_dates 中的每个日期转换为覆盖整个日期的范围。
array_of_dates = array_of_dates.map {|date| date.beginning_of_day..date.end_of_day}

这将把每个日期转换为一个范围,例如(Mon 27 Oct 2014 00:00:00..Mon 27 Oct 2014 23:59:59)
现在使用下面的查询格式来查找事件:
Event.where(date: array_of_dates)

谢谢您的帮助! :) - user4187589

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接