Ruby on rails 在生成查询时将创建的时间强制转换为时间戳

Ruby on rails 在生成查询时将创建的时间强制转换为时间戳,ruby-on-rails,ruby,postgresql,activerecord,Ruby On Rails,Ruby,Postgresql,Activerecord,我有一个关于检索数据库数据的问题 我有一个模型通知,它在处创建了标准Rails属性。 您可能知道,在访问时,此属性是ActiveSupport::TimeWithZone对象,它确实具有超精确的值,您可以通过将其强制转换为\u i甚至强制转换为\u f 所以现在我想将where子句写入Notification模型,并查找在特定时间后创建的通知。但由于可能在同一秒内创建了多个通知,我希望查询更加精确,因此我尝试编写如下子句: Notification.where('created_at >

我有一个关于检索数据库数据的问题

我有一个模型
通知
,它在处创建了标准Rails属性
。
您可能知道,在访问时,此属性是
ActiveSupport::TimeWithZone
对象,它确实具有超精确的值,您可以通过将其
强制转换为\u i
甚至
强制转换为\u f

所以现在我想将
where
子句写入
Notification
模型,并查找在特定时间后创建的通知。但由于可能在同一秒内创建了多个通知,我希望查询更加精确,因此我尝试编写如下子句:

Notification.where('created_at > ?', timestamp)
而且它似乎不起作用


如何将created_转换为值,以便能够将其与时间戳进行比较?

时间戳比较工作正常,即使是在亚秒级

尝试试验:

# create two users
u1 = User.create(name:'user1')
u2 = User.create(name:'user2')
d1 = u1.created_at
d2 = u2.created_at

# update d1 so that it's exact second (milliseconds = 0)
# update d2 so that it's exactly d1 + 0.5sec
d1 = d1 - (d1.to_f - d1.to_i)
d2 = d1 + 0.5
u1.created_at = d1
u2.created_at = d2

# now create a timestamp just between d1 and d2
d0 = d1 + 0.25

# those queries now give expectable results
User.where('created_at<?',d0).count # => 1
User.where('created_at>?',d0).count # => 1
但是


它没有超精确的值<代码>至_i
。它仍然是以秒为单位,而不是以毫秒为单位。那么呢?它是否具有更精确的值?这取决于您选择的数据库是否存储毫秒。将datetime转换为时间戳(反之亦然)并不会使其更精确,最终是一样的。在某些事情上打电话给_f也不能让它更精确。2.0并不比2更精确。两者都等于2。我使用PosggreSQL,它的日期字段分辨率似乎为1微秒。但我仍然不知道如何以这种精度进行查询
User.where('created_at=?',d1).count # => 0
User.where('created_at=?',d2).count # => 0
d1 = u1.created_at
User.where('created_at=?',d1).count # => 1