2010-11-24 28 views
8

我把这个应用程序控制器:的Rails 3:设置时区,以当前用户的时区

before_filter :set_timezone 

def set_timezone 
Time.zone = current_user.time_zone 
end 

但我总是得到错误:

undefined method time_zone for #<User:0xa46e358> 

,我只是不知道为什么...

我希望有人能帮助

+0

你为什么认为这应该起作用? current_user.time_zone – 2010-11-24 16:51:12

+0

http://ryandaigle.com/articles/2008/1/25/what-s-new-in-edge-rails-easier-timezones – Max 2010-11-24 16:58:03

回答

11

马克斯 - 在ryandaigle.com article你提到的链接this writeup,你需要创建一个迁移添加“的time_zone”作为属性用户

(这是从文章中轨2.x的语法)

$ script/generate scaffold User name:string time_zone:string 
$ rake db:migrate 

<%= f.time_zone_select :time_zone, TimeZone.us_zones %> 

这就是为什么你的.time_zone返回一个method_missing - 你还没有在用户上存储time_zone。

+0

Thx有帮助。 – Max 2010-11-24 17:19:23

25

此外杰西的答案,我想补充一点,你可以大致避免添加以dB为单位的新列,只是建立在用户模式和化妆使用的cookie的自定义方法来获取用户的 时区:

在客户端(JS):

function set_time_zone_offset() { 
    var current_time = new Date(); 
    $.cookie('time_zone', current_time.getTimezoneOffset()); 
} 


在应用控制器

before_filter :set_timezone 

def set_timezone 
min = request.cookies["time_zone"].to_i 
Time.zone = ActiveSupport::TimeZone[-min.minutes] 
end 
2
function set_time_zone_offset() { 
    var current_time = new Date(); 
    $.cookie('time_zone', current_time.getTimezoneOffset()); 
} 

这是不正确的,因为时间偏移不是恒定的,这取决于夏令时间段。 Rails在拨打ActiveSupport :: TimeZone [-min.minutes]时需要标准时间偏移。

例如:在法国,日期为09/03/2013 10:50:12 +02:00,您的javascript将返回-120作为偏移量,其中ActiveSupport将需要-60来解析法国时区。

然后你需要检查这是否是daylight saving time period in JS那么如果是这种情况,你将不得不减去一小时的偏移量以获得Rails使用的正确值。