【发布时间】:2016-02-14 04:21:04
【问题描述】:
在我的 Rails 应用程序中,我想在timezone 中显示用户偏好设置的所有时间实例,而不是 UTC。
这是一个常见问题,我已经看到将默认 UTC 更改为 one specific timezone(如 EDT)的解决方案。不过,我想让时间动态化,并且我想在服务器端的 time_formats.rb 初始化程序中执行此操作。换句话说,用户应该能够根据自己的喜好查看 GMT 0、GMT +1 或 GMT +2 的时间。
我以一种在本地工作但在推送到 Heroku 时中断的方式完成了此操作。这是我设置的。
首先,我在我的 Devise 用户模型中添加了 timezone 作为一列。
class AddTimezoneToUsers < ActiveRecord::Migration
def change
add_column :users, :timezone, :string
end
end
接下来,我正在格式化我的time-formats.rb:
Time::DATE_FORMATS[:default] = in_time_zone("%I:%M %p")
在本地,这很好用。我可以在“设置”中更改我的时区偏好,它会在所有时间实例中进行调整。但是,由于以下原因,我对 Heroku 的推送失败了:
.../bundle/ruby/2.2.0/gems/activesupport-4.0.4/lib/active_support/values/time_zone.rb:283:
warning: circular argument reference - now
remote: rake aborted!
remote: NoMethodError: undefined method `in_time_zone' for main:Object
从Rails class documentation 中找到in_time_zone,为什么它在本地工作但在Heroku 中导致方法问题?
编辑1:刚刚有了另一个想法,我想添加一些其他调试。由于这是一个方法错误,我现在检查了我的 ApplicationController。
before_filter :set_timezone
def set_timezone
tz = current_user ? current_user.timezone : nil
Time.zone = tz || ActiveSupport::TimeZone["London"]
end
由于在用户更改current_user.timezone 之前将默认设置为伦敦,我认为它不应该冲突。想包括虽然。
【问题讨论】:
标签: ruby-on-rails datetime heroku