Ruby on Rails query by datetime range ( last 24, 48, etc... hours )

11,818

Solution 1

Ensure that the timezones you have recorded within the database and those your rails app is outputting are equal. This can sometimes cause an issue. Otherwise try this named scope:

 class User < ActiveRecord::Base
   named_scope :last_loggedin_before, lambda { |time_ago| { :conditions => ['last_login_at   < ?', time_ago] } }
   named_scope :last_loggedin_within, lambda { |time_ago| { :conditions => ['last_login_at   > ?', time_ago] } }
 end

allowing you to do:

 User.last_loggedin_before 24.hours.ago

or

 User.last_loggedin_within 24.hours.ago

Solution 2

Old question, but here's newer syntax:

User.where(last_login_at: 3.days.ago..DateTime.now)
Share:
11,818
Michael
Author by

Michael

Updated on June 21, 2022

Comments

  • Michael
    Michael almost 2 years

    I'm trying to build a query that will search for recent entries based on column 'last_login_at'. This is a datetime field with time zone (i.e. Time.zone.now) When I execute

    User.find(:all, :conditions => ["last_login_at < ?", 24.hours.ago])
    

    I get nothing.

    Alternatively I can define today as Time.zone.today and yesterday as Time.zone.today - 1.day and run

    User.find(:all, :conditions => ["last_login_at between ? and ?", today, yesterday])
    

    and it still returns 0 results. I know there are some entries that fall into this category.

  • Michael
    Michael over 14 years
    It seems that the timezones im comparing are both PST -08:00, so im still stuck there ... The named scopes should work great! thanks
  • Blake
    Blake about 11 years
    This works great, thanks. One note - named_scope has changed to just 'scope' (I'm on Rails 3.2.11).
  • A moskal escaping from Russia
    A moskal escaping from Russia about 5 years
    That's nice, but keep in mind 3.days.ago doesn't start from the beginning of the day (00), so it'll skip records created before that day but before that time. Check 3.days.ago.beginning_of_day.