在Ruby 2.4.1上运行的Rails 5.0.2 API应用程序。
application.rb
config.time_zone = "UTC"
config.active_record.default_timezone = :utc
模型查询
weight_entry = @current_user.weight_entries
.where(taken_on: Time.now.beginning_of_day..Time.now.end_of_day)
.first
执行以下查询
WeightEntry Load (3.2ms) SELECT "weight_entries".*
FROM "weight_entries" WHERE "weight_entries"."user_id" = $1
AND ("weight_entries"."taken_on" BETWEEN $2 AND $3)
ORDER BY "weight_entries"."id"
ASC LIMIT $4 [["user_id", 3],
["taken_on", 2017-06-07 06:00:00 UTC],
["taken_on", 2017-06-08 05:59:59 UTC], ["LIMIT", 1]]
正如您所看到的,尽管全局设置了UTC,但针对数据库的ActiveRecord查询仍在时间组件中使用偏移量(6小时):
["taken_on", 2017-06-07 06:00:00 UTC],
["taken_on", 2017-06-08 05:59:59 UTC], ["LIMIT", 1]]
我希望,UTC是整个应用程序的默认值,时间戳看起来更像是这样:
["taken_on", 2017-06-07 00:00:00 UTC],
["taken_on", 2017-06-08 23:59:59 UTC], ["LIMIT", 1]]
如果我将模型查询更改为此(手动插入utc):
weight_entry = @current_user.weight_entries
.where(taken_on: Time.now.utc.beginning_of_day..Time.now.utc.end_of_day)
.first
我得到了预期的结果:
["taken_on", 2017-06-07 00:00:00 UTC],
["taken_on", 2017-06-08 23:59:59 UTC], ["LIMIT", 1]]
每次在通过Rails插入和查询数据库时使用时间元素时是否真的需要插入.utc,即使我已将UTC设置为默认时区?
我在这里缺少什么?
答案 0 :(得分:4)
您应该使用Time.zone.now
代替Time.now
或Time.now.utc
这里有很好的解释
https://rails-bestpractices.com/posts/2014/10/22/use-time-zone-now-instead-of-time-now/