ruby-on-rails - Rails 将 config.active_record.default_timezone 设置为 :utc or :local 以外的值

标签 ruby-on-rails postgresql rails-activerecord

我将我的应用时区设置为太平洋。

# application.rb: 
config.time_zone = 'Pacific Time (US & Canada)'  

我的生产服务器时间设置为太平洋时间。但是 ActiveRecord 将每个 session 的 postgres 时区设置为“UTC”:

[1] pry(main)> ActiveRecord::Base.connection.execute("show timezone").getvalue(0,0)
  (0.2ms)  show timezone
=> "UTC"  

docs假设我对 config.active_record.default_timezone 只有两个选项是 :utc:local

使用 :local 适合生产环境,但我的开发服务器位于不同的时区。

我知道通常建议将所有时区设置保留为默认 UTC,但我的应用程序广泛使用 postgres 的时间和日期函数来处理 ETL 作业、复杂的数据分析查询等。我宁愿让 postgres 成为我的“单一来源”真相”而不是 rails/ruby,所以我对告诉我在 UTC 中做所有事情的答案不感兴趣

编辑:我已确认 config.time_zone 已正确设置:

[6] pry(main)> Rails.application.config.time_zone
=> "Pacific Time (US & Canada)"

并且 config.active_record.default_timezone 设置为 :local

[9] pry(main)> Rails.application.config.active_record.default_timezone
=> :local

在同一个窥探 session 中:

[10] pry(main)> ActiveRecord::Base.connection.execute("show timezone").getvalue(0,0)
   (0.2ms)  show timezone
=> "Asia/Bangkok"

最佳答案

查看 PostgreSQL 适配器 source在 github 上,我看到检查变量散列是否存在“时区”键。

      variables = @config.fetch(:variables, {}).stringify_keys

      # If using Active Record's time zone support configure the connection to return
      # TIMESTAMP WITH ZONE types in UTC.
      unless variables["timezone"]
        if ActiveRecord::Base.default_timezone == :utc
          variables["timezone"] = "UTC"
        elsif @local_tz
          variables["timezone"] = @local_tz
        end
      end

PostgreSQLAdapter docs显示 :variablesconfig/database.yml 中的一个选项,所以我刚刚添加了 variables: {timezone: 'US/Pacific'}到 database.yml。

# database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  variables: {timezone: 'US/Pacific'}

有点奇怪,你必须在这里而不是在 config/ 中设置它,但它有效。

关于ruby-on-rails - Rails 将 config.active_record.default_timezone 设置为 :utc or :local 以外的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52529867/

相关文章:

ruby-on-rails - 事件模型序列化器将所有日期转换为秒

postgresql - INSERT 和 COPY 的区别

sql - HAVING 子句有什么问题?

ruby-on-rails - 大表上的 Rails 计算

ruby-on-rails - 按用户个人资料过滤微博提要

ruby-on-rails - 跨越从形式到更有趣的对象的 Rails 学习和开发障碍

ruby-on-rails - Turbolinks 和 3d 派对插件问题?

ruby-on-rails - 从字符串中提取标签

ruby-on-rails - `require:` 在 Rails gemfile 中意味着什么?

postgresql - 如何减少具有有序结果的 postgresql IN 查询的索引扫描时间?