ActiveRecord:使用where子句时不考虑毫秒数 [英] ActiveRecord: milliseconds aren't taken into account when using a where clause

查看:124
本文介绍了ActiveRecord:使用where子句时不考虑毫秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用rails api和iOS客户端进行项目,使用updated_at字段作为参考,以检测客户端最后一次提取后服务器上的修改。

I'm working on a project with a rails api and an iOS client, using the updated_at field as the reference to detect modifications on the server that happened after the last pull from the client.

updated_at datetime的精度以毫秒为单位,这意味着

The updated_at datetime has a precision in milliseconds, meaning that

Model.updated_at.to_f

返回类似1368977381.063427的内容。
这被发送到格式化为2013-05-19T15:29:41.063427000Z的客户端。

returns something like "1368977381.063427". This is sent to the client formatted as "2013-05-19T15:29:41.063427000Z".

麻烦的是,当我收到该datetime后从客户端解析它并用它进行查询,毫秒数将丢失。

The trouble is, when I get that datetime back from the client, parse it and query with it, the milliseconds are lost.

last_update = DateTime.strptime("2013-05-19T15:29:41.063427000Z", "%Y-%m-%dT%H:%M:%S.%N%z")
Model.where("updated_at > ?", last_update)

与做的一样好

last_update = DateTime.strptime("2013-05-19T15:29:41Z", "%Y-%m-%dT%H:%M:%S%z")
Model.where("updated_at > ?", last_update)

因此,我总是得到至少有一个结果,当我不应该没有,因为毫秒被截断。

As a result, I always get at least one result when I should get none, because the milliseconds are truncated.

如何在我的查询中考虑到这些?

How can I take those into account in my query ?

推荐答案

尝试

Model.where("updated_at > ?", last_update.strftime("%Y-%m-%dT%H:%M:%S.%N%z"))



您也可以将此格式设置为数据库中DateTime的标准格式。在初始化器中):

You can also set this format as the standard format for DateTime in databases by setting (i.e. in an initiallizer):

Time::DATE_FORMATS[:db]= '%Y-%m-%dT%H:%M:%S.%N%z'

然后您的原始查询再次工作:

then your original query works again:

Model.where("updated_at > ?", last_update)

查看<$ c的 Rails API $ c> DateTime.to_s (aka .to_formated_s)

See the Rails API for DateTime.to_s (aka .to_formated_s)

这篇关于ActiveRecord:使用where子句时不考虑毫秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆