Rails 5 API:全局将config.time_zone设置为UTC

时间:2017-06-08 00:39:24

标签: ruby-on-rails ruby datetime activerecord timezone

在Ruby 2.4.1上运行的Rails 5.0.2 API应用程序。

  1. 将config中的time_zone设置为“UTC”
  2. 将ActiveRecord default_timezone设置为:utc
  3. 配置更改后,应用程序重启多次
  4. 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设置为默认时区?

    我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)