Mark Denn
Mark Denn

Reputation: 2304

How to find records that created more than 10 minutes ago but not less

I am building a Rails 5 app and I want to check if there is an activitiy for the otype "update_product" done the last 10 minutes.

I tried this and get an error

start_date = DateTime.now
end_date = DateTime.now - 10.minutes
Activity.where("otype = ? AND sku = ? AND created_at < ?", 'update_product', '8888', start_date..end_date)

I also tried this but that gets ALL that is older than 10 minutes but I only want to check if there was an activity that was made between 0 and 10 minutes ago.

Activity.where("otype = ? AND sku = ? AND created_at < ?", 'create_product', output['variants'][0]['sku'], 10.minutes.ago)

So what I am looking for is to make sure there is no matching Activity records that is created less than 10 minutes ago.

Upvotes: 1

Views: 2359

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33430

You can use exists? if the query is just to see if there at least one record and return a boolean:

Activity.where(otype: 'update_product').where('created_at <= ?', 10.minutes.ago).exists?

Which can be shortened to just where(...).exists?(...)

Activity.where(otype: 'update_product').exists?(['created_at >= ?', 10.minutes.ago])

To filter the rows depending on their created_at column, which happens to be of timestamp data type, you can use a range, which ActiveRecord interprets using >= as well:

Activity.where(otype: 'update_product', created_at: ..5.minutes.ago).exists?
# SELECT 1 AS one
# FROM "activities"
# WHERE "activities"."otype" = $1
# AND "activities"."created_at" <= $2
# LIMIT $3  [["otype", "update_product"], ["created_at", "2020-07-01 09:09:09.031745"], ["LIMIT", 1]]

Notice beginless ranges were just added to Ruby 2.7.

Upvotes: 1

Related Questions