简体   繁体   English

如何在Rails 4中动态更改ActiveRecord的默认时区?

[英]How to change default timezone dynamically for ActiveRecord in Rails 4?

In my application_controller.rb 在我的application_controller.rb

before_action :set_user_time_zone

def set_user_time_zone
  Time.zone = 'Kolkata'
end

I added the above code to change the Time-zone dynamically. 我添加了上面的代码来动态更改时区。 But it does not change the Time-zone.I have time_zone field for each user in user table, I want to change time_zone according to current user. 但是它不会更改时区。我在用户表中为每个用户都有time_zone字段,我想根据当前用户更改time_zone。 How to change Time.Zone dynamically? 如何动态更改Time.Zone?

You could put a filter in your application controller that will apply to all actions in all controllers to use the user's time zone when dealing with dates and times. 你可以把你的应用程序控制器的过滤器使用日期和时间处理时将适用于所有行动,所有控制器使用用户的时区。

This code to do that comes from Sebastian Porto and assumes you have a :time_zone column for users. 此代码来自塞巴斯蒂安·波尔图,并假设您为用户提供了:time_zone列。 It defaults to using UTC if it can't get the user 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM