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 m开发者_如何转开发ethod time_zone for #<User:0xa46e358>
and I just don't know why...
I hope someone can help
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
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.
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.
精彩评论