Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: setting the timezone to the current users timezone

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

like image 212
Max Avatar asked Nov 24 '10 16:11

Max


3 Answers

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 
like image 64
yaka Avatar answered Nov 19 '22 01:11

yaka


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.

like image 20
Jesse Wolgamott Avatar answered Nov 19 '22 02:11

Jesse Wolgamott


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.

like image 2
lcobos Avatar answered Nov 19 '22 00:11

lcobos