Reputation: 13835
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?
Upvotes: 18
Views: 19954
Reputation: 7405
In Rails 5.1 and greater, you can use all_day
instance method like this:
today = Date.today - 1
todaysReport = Report.where(created_at: today.all_day).find_by_user_id(user.id)
Upvotes: 4
Reputation: 6672
In postgres, you can cast a timestamp as a date. For example:
Report.where("created_at::date = ?", Date.today - 1)
Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL
Upvotes: 16
Reputation: 176
It can also be TimeWithZone if time zone specified in application config. To get Date to TimeWithZone you have to do like Date.today.to_time.in_time_zone.
Upvotes: 1
Reputation: 14881
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 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)
Upvotes: 6
Reputation: 12749
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])
Upvotes: 23
Reputation: 35298
Have you tried using #to_datetime
, which Rails adds to the Date
and Time
classes?
Report.where(:created_at => today.to_datetime).find_by_user_id(user.id)
Actually surprised AR doesn't handle this for you.
Upvotes: -5