Search code examples
ruby-on-railsrubyruby-on-rails-5rails-activerecord

query less than infinity on creation date in active record


I need to filter all users that were created two months ago from today's date (today's date has to be dynamic and not fixed). But the active record doesn't understand exactly what I want. I make this query:

range_expired = ((2.months.ago).end_of_day)..((Date.today).end_of_day)
current_status = StudentStatusChange.where(created_at < range_expired)

Solution

  • If you need all records from 2 months ago (exclude) to today's date (include) as you tried, you can use something like this

    range_expired = 2.months.ago.end_of_day..Date.today.end_of_day
    
    StudentStatusChange.where(created_at: range_expired)
    

    Other variants:

    # works in ruby >= 2.6
    range_expired = 2.months.ago.end_of_day..
    StudentStatusChange.where(created_at: range_expired)
    
    StudentStatusChange.where("created_at > ?", 2.months.ago.end_of_day)
    StudentStatusChange.where("created_at > :two_months_ago", two_months_ago: 2.months.ago.end_of_day)