我刚注意到一些让我有点麻烦的事情。
我正在创建一个对象。该对象使用以下内容进入数据库:
created_at: "2015-11-12 08:37:35.413663"
我没有意识到它存储超出.413
您可以通过执行以下操作确认已保存,而不仅仅是为了我们的观看乐趣:object.created_at.nsec #=> 413663000
当我的前端收到我的JSON时,created_at属性变为:"2015-11-12T08:37:35.413Z"
,这是我期望的。这里的问题是我们丢失了有价值的信息,因为现在我们没有633微秒。
的确,如果你做"2015-11-12T08:37:35.413Z".to_time.nsec #=> 413000000
。
这意味着当您执行以下操作时,您将不会获得任何项目:
Object.where(created_at: object.created_at.as_json).first #=> nil
如何缓解这种情况?如何计算微秒,或者更确切地说,查询created_at,只需毫秒精度。
答案 0 :(得分:2)
Ultimately, I decided on changing the datetime columns in my DB.
I basically applied the following wherever relevant in a migration:
change_column table, column, :datetime, limit: 3
That successfully makes sure that my :datetime columns all only go to the milliseconds.
I think it is a good change because when the sole purpose of my back-end is to render a JSON API, then I think through and through it should be cohesive. JSON API standards are ISO 8601. As such, I'd like my DB to adhere to that.
答案 1 :(得分:0)
DateTime.now.to_s
不会返回小数秒,因为您需要更高的精度,您可以在创建的参数中使用DateTime.now.iso8601(10)
。
m = ModelName.create(created_at: DateTime.now.iso8601(10))
或
m = ModelName.create()
m.created_at = DateTime.now.iso8601(10)
m.save
我尝试过有点类似于你所描述的测试:
p=Product.create(created_at: DateTime.now.iso8601(10))
p.created_at.nsec
=> 61103188
Product.where(created_at: p.created_at)
=> #<ActiveRecord::Relation [#<Product id: 172, manufacturer: nil, created_at: "2015-11-12 10:11:31", updated_at: "2015-11-12 10:11:31", avatar: nil>]>