9

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

Max
  • 145
  • 2
  • 2
  • 4

3 Answers3

27

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 
yaka
  • 914
  • 1
  • 9
  • 16
  • 10
    +1 for trying to determine the timezone from information available without user explicitly providing it. This is a rather unreliable method of doing this, though. In a production environment you would want to use something [like this](https://bitbucket.org/pellepim/jstimezonedetect/src/ab0cfa941246/detect_timezone.js) to detect the timezone more accurately, and you should always store this and allow the user to override it. – coreyward Oct 09 '11 at 17:36
  • Using cookies its work perfect but what we can do if someone clear cookies or not allow to cookies then? – user1780370 Dec 15 '15 at 06:49
13

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.

Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109
  • Is there a way to get the timezone from a user that is not in the database and is just visiting the site? – Max Nov 24 '10 at 17:20
  • 1
    This might be helpful (get it in javascript)- http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp – Jesse Wolgamott Nov 24 '10 at 17:45
2
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.

Community
  • 1
  • 1
lcobos
  • 31
  • 1