trisignia
trisignia

Reputation: 1183

ActiveRecord scope to find records created today?

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?

Upvotes: 1

Views: 2480

Answers (3)

kuboon
kuboon

Reputation: 10181

How about this?

  scope :today, lambda { 
    where("created_at >= ? and created_at <= ?", 
           Date.today.beginning_of_day.utc, Date.today.end_of_day.utc)
  }  

Upvotes: 0

Chirantan
Chirantan

Reputation: 15634

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.

timezone = current_user.timezone # Mountain Time (US & Canada)
users_current_time = ActiveSupport::TimeZone[timezone].parse(Time.now.to_s)

users_current_time.beginning_of_day and users_current_time.end_of_day should 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.timezone before_filter of all actions and use it in the scope. This railscast gives fair idea about how to go about doing that.

Upvotes: 3

brycemcd
brycemcd

Reputation: 4513

If you're using mysql, then I think you just want to match on the day, not the time right? Stated another way, you want all records from Dec. 1st. Between 12:00am and 11:59pm on Dec. 1st is implied if you just search on date.

 scope :today, lambda { 
    where("created_at = ?",
           Time.now.strftime("%Y-%d-%m")
  } 

Something like that should work

Upvotes: 1

Related Questions