【问题标题】:Cast created_at to timestamp when building query构建查询时将 created_at 转换为时间戳
【发布时间】:2015-09-25 23:44:52
【问题描述】:

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

我有一个模型Notification,它有标准的Rails 属性created_at。 您可能知道,虽然是ActiveSupport::TimeWithZone 访问对象,但该属性确实拥有超精确的值,您可以通过强制转换to_i 甚至to_f 来访问它

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

Notification.where('created_at > ?', timestamp)

它似乎不起作用。

如何转换 created_at 值才能将其与时间戳进行比较?

【问题讨论】:

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

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

尝试实验:

# 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

但要小心:

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

【讨论】:

    猜你喜欢
    • 2014-09-19
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2021-12-05
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多