Rails 3: setting the timezone to the current users

2020-01-29 05:27发布

I put this in Application Controller:

before_filter :set_timezone 

def set_timezone  
Time.zone = current_user.time_zone 
end  

But I always get the error:

undefined method time_zone for #<User:0xa46e358>

and I just don't know why...

I hope someone can help

3条回答
爷的心禁止访问
2楼-- · 2020-01-29 05:53

Further to Jesse's answer, I should add that you can generally avoid adding a new column in db and just create a custom method in user model and make use of cookie to get the user's timezone:

in client-side (js):

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


in Application Controller:

before_filter :set_timezone 

def set_timezone  
 min = request.cookies["time_zone"].to_i
 Time.zone = ActiveSupport::TimeZone[-min.minutes]
end 
查看更多
对你真心纯属浪费
3楼-- · 2020-01-29 06:02

Max -- the ryandaigle.com article you mentioned links to this writeup where you need to create a migration to add "time_zone" as an attribute to the user

(this is from the article, in rails 2.x syntax)

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

later

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

That's why your .time_zone is returning a method_missing -- you haven't stored the time_zone on the user yet.

查看更多
\"骚年 ilove
4楼-- · 2020-01-29 06:12
function set_time_zone_offset() {
  var current_time = new Date();
  $.cookie('time_zone', current_time.getTimezoneOffset());
}

This is not correct, because time offset is not constant, it depends on daylight saving time periods. Rails expects the standard time offset when calling ActiveSupport::TimeZone[-min.minutes].

ex: in France at date 09/03/2013 10:50:12 +02:00, your javascript will return -120 as offset where ActiveSupport will need -60 to resolve France timezone.

Then you need to check if this is a daylight saving time period in JS then if this is the case you will have to substract one hour to the offset to get the right value used by Rails.

查看更多
登录 后发表回答