This has got to be an easy thing to do, but I think that Rail’s timezone implementation is throwing off my work…
How can I create a scope in Rails 3 (and ruby 1.9.2) to query for records created today?
Currently, I’m doing this:
scope :today, lambda {
where("created_at >= ? and created_at <= ?",
Date.today.beginning_of_day, Date.today.end_of_day)
}
And it doesn’t appear to be working as it should. I want “today” to represent the 24 hour period from 12am to 11:59pm for a user’s local timezone. Do I need to convert the date to UTC or something?
You will need to consider user’s timezone. That is, beginning of day and end of day in the user’s timezone. For that, first parse the current time in user’s timezone. You can set the zone to user’s timezone and do the calculation or you can parse the time directly using a variation of the following code.
users_current_time.beginning_of_dayandusers_current_time.end_of_dayshould generate the right time range (which you app would convert to UTC and fire the query, if UTC is your applications timezone)If you want to do that with scopes only, then I suggest you set the
Time.zone = current_user.timezonebefore_filterof all actions and use it in the scope. Thisrailscast gives fair idea about how to go about doing that.