3

I need to get records created 30 minutes ago from Time.now. I'm using a cron and I want to fire the cron once ever minute.

I essentially need this except it should ignore the seconds so that if Time.now == Wed, 31 Jan 2018 18:00:31 +0000 then a record with created_at = "Wed, 31 Jan 2018 17:30:23 +0000 should match.

Here is the query I have so far which doesn't work because the time is improperly evaluated.

Cart.joins(:cart_addresses).group('carts.id').where(created_at: Time.now - 30.minutes).each do |i|
  puts i.id
end
Cannon Moyer
  • 3,014
  • 3
  • 31
  • 75

2 Answers2

3

Please try below query:

# if current time is 3:00:03
# it will return carts created at 2:30:00 -> 2:30:59
from_mins_ago = 30.minutes.ago.change(sec: 0)
to_mins_ago   = from_mins_ago.change(sec: 59) 
Cart.joins(:cart_addresses).group('carts.id').where(created_at: from_mins_ago..to_min_ago).pluck('carts.id')
Tai
  • 1,244
  • 9
  • 11
0

You could use a range.

Cart.joins(:cart_addresses).group('carts.id').where(created_at: 30.minutes.ago..DateTime.now)

There's a lot of solutions.

More: Rails ActiveRecord date between

Josh Brody
  • 5,153
  • 1
  • 14
  • 25