我将我的应用时区设置为太平洋。
# 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显示 :variables
是 config/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/