horseyguy
horseyguy

Reputation: 29915

How to specify a date range for active record?

I have a background job that runs at midnight UTC every night. I need to grab all new records for an active record model whose updated_at is >= the previous midnight (UTC) and the current day's midnight UTC.

What is the best way to do this?

so i need something like:

MyRecord.where(updated_at: prior_utc_midnight..tonight_utc_midnight)

But i'm unsure how to wrangle the Time/Date and DateTime classes to do what i want.

Thanks!

Upvotes: 0

Views: 2672

Answers (3)

Andy Day
Andy Day

Reputation: 935

It's a little wonky, but I think this works:

MyRecord.where("created_at > ? AND created_at < ?", Date.today.to_datetime.new_offset(0) - 1.day, Date.today.to_datetime.new_offset(0))

Upvotes: 0

Deepak Mahakale
Deepak Mahakale

Reputation: 23711

You can make use of beginning_of_day and end_of_day methods available.

These helpers will give you the midnight time

MyRecord.where(created_at: Date.today.beginning_of_day..Date.today.end_of_day)

#=> SELECT "my_records".* FROM "my_records" WHERE ("my_records"."created_at" BETWEEN '2017-02-24 00:00:00.000000' AND '2017-02-24 23:59:59.999999')

Also, take a look at these methods

Upvotes: 2

abstractx1
abstractx1

Reputation: 459

MyRecord.where("updated_at >= '#{Date.today}' and updated_at < '#{Date.today.next_day}'")

The only thing to consider is the timezone of the data in the table. If that is UTC also, then this query should give you the results you have asked for.

Upvotes: -1

Related Questions