我正在构建一个 Rails 5 应用程序,我想检查过去 10 分钟内完成的 otype "update_product" 是否有活动。
我试过这个,但出现错误
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)
我也尝试过这个,但这得到了超过 10 分钟的所有内容,但我只想检查是否有在 0 到 10 分钟前进行的活动。
Activity.where("otype = ? AND sku = ? AND created_at < ?", 'create_product', output['variants'][0]['sku'], 10.minutes.ago)
因此,我正在寻找的是确保没有不到 10 分钟前创建的匹配活动记录。
如果查询只是为了查看是否至少有一个记录并返回布尔值,则可以使用exists?
:
Activity.where(otype: 'update_product').where('created_at <= ?', 10.minutes.ago).exists?
可以缩短为where(...).exists?(...)
Activity.where(otype: 'update_product').exists?(['created_at >= ?', 10.minutes.ago])
若要根据行的created_at
列(恰好是时间戳数据类型(筛选行,可以使用 ActiveRecord 也使用>=
解释的区域:
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]]
请注意,无开始范围刚刚添加到 Ruby 2.7 中。