Rails 3 DateTime Comparison w/ Date In An ActiveRecord Query

前端 未结 4 1327
死守一世寂寞
死守一世寂寞 2021-02-09 00:58

I\'m trying to search a model for any dates equal to a specific date while omitting the timestamp. In Rails I could simply execute this as DateTime.to_date == somedate

相关标签:
4条回答
  • 2021-02-09 01:42

    DateTime class have two usefull methods to do this: beginning_of_day and end_of_day.

    For this case, in which you have a Date object, you might do:

    Foo.where('created_at >= #{Date.today.to_time.beginning_of_day} AND 
               created_at <= #{Date.today.to_time.end_of_day}')
    

    Notice that you have to transform the Date object to a DateTime object

    0 讨论(0)
  • 2021-02-09 01:45

    I would do something like...

    someday = Date.today
    Foo.where( :created_at => (someday)..(someday + 1.day) )
    

    This would capture all created_at dates between midnight on someday and someday + 1. This is inclusive (so it would include a Foo created bang on midnight on the +1 day) but may be 'just good enough' for your needs without messing with timestamps.

    For niceness, I would wrap it up as a scope

    scope :on_day, ( lambda do |someday|
      where( :created_at => (someday)..(someday + 1.day) )
    end )
    

    So

    Foo.on_day( Date.yesterday ).count
    

    is nicely readable.

    0 讨论(0)
  • 2021-02-09 01:50

    With scope:

    scope :on_day, (lambda do |day|
       where(date: day.beginning_of_day..day.end_of_day)
    end)
    

    Using:

    Foo.on_day(Date.today).count
    
    0 讨论(0)
  • 2021-02-09 01:55

    Try created_at >= some_day_with_00:00:00 timestamp and create_at < some_day_plus_one_with_00:00:00 timestamp

    0 讨论(0)
提交回复
热议问题