【问题标题】:How to change default timezone dynamically for ActiveRecord in Rails 4?如何在 Rails 4 中动态更改 ActiveRecord 的默认时区?
【发布时间】:2015-11-13 14:51:45
【问题描述】:

在我的application_controller.rb

before_action :set_user_time_zone

def set_user_time_zone
  Time.zone = 'Kolkata'
end

我添加了上面的代码来动态更改时区。但它不会更改时区。我在用户表中为每个用户都有 time_zone 字段,我想根据当前用户更改 time_zone。如何动态更改 Time.Zone?

【问题讨论】:

  • 我认为blog 是您所需要的。

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


【解决方案1】:

您可以在应用程序控制器中放置一个过滤器,该过滤器将应用于所有控制器中的所有操作,以便在处理日期和时间时使用用户的时区。

执行此操作的代码来自 Sebastian Porto,并假设您有一个供用户使用的 :time_zone 列。如果无法获取用户时区,则默认使用 UTC。

class ApplicationController < ActionController::Base
  around_filter :set_time_zone

  def set_time_zone(&block)
    time_zone = current_user.try(:time_zone) || 'UTC'
    Time.use_zone(time_zone, &block)
  end
end

【讨论】:

  • 如何检查 time_zone 是否设置为 current_user(:time_zone)..? @托比
  • Time.zone.name == current_user.time_zone
猜你喜欢
  • 2012-11-25
  • 2011-09-01
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2011-09-16
  • 2019-05-19
相关资源
最近更新 更多