[英]Comparing a Date to the Datetime Created_at in rails3
So I'm trying to do things like so:所以我正在尝试做这样的事情:
today = Date.today - 1
todaysReport = Report.where(:created_at => today).find_by_user_id(user.id)
The problem is created_at is a datetime, so it won't find any matches..Any suggestions?问题是 created_at 是一个日期时间,所以它不会找到任何匹配项..有什么建议吗?
You probably want something like this:你可能想要这样的东西:
yesterday = Time.now - 1.day
user = User.find(user_id)
todaysReport = user.reports.where(["created_at >= ? AND created_at <= ?", yesterday.beginning_of_day, yesterday.end_of_day])
In postgres, you can cast a timestamp as a date.在 postgres 中,您可以将时间戳转换为日期。 For example:例如:
Report.where("created_at::date =?", Date.today - 1)
Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL 从 PostgreSQL 中的时间戳中提取日期 (yyyy/mm/dd)
You need to compare against a range from one midnight to the next.您需要与从一个午夜到下一个午夜的范围进行比较。 Also, this is a good candidate for making your own class method for higher flexibility.此外,这是制作您自己的 class 方法以获得更高灵活性的良好候选者。
class Report
# All reports created on the specified Date
def self.created_on(date)
where(['created_at >= ? AND created_at < ?', date, date + 1])
end
end
# Find all reports created yesterday by our user
Report.created_on(Date.today - 1).where(:user_id => user.id)
It can also be TimeWithZone if time zone specified in application config.如果在应用程序配置中指定时区,它也可以是 TimeWithZone。 To get Date to TimeWithZone you have to do like Date.today.to_time.in_time_zone.要获得 TimeWithZone 的日期,您必须像 Date.today.to_time.in_time_zone 一样。
Have you tried using #to_datetime
, which Rails adds to the Date
and Time
classes?您是否尝试过使用 Rails 添加到Date
和Time
类的#to_datetime
?
Report.where(:created_at => today.to_datetime).find_by_user_id(user.id)
Actually surprised AR doesn't handle this for you.实际上很惊讶 AR 并没有为你处理这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.