1

I have a User model, which allow user to provide their own time zone. User can choose their own time zone using the time_zone_select. So we will store something like Pacific Time (US & Canada) in database.

My Rails 3 application default setting is using Pacific Time (US & Canada). So all the time display is in this time zone.

May I change the time time display based on user time zone? For example, User A will see all the time displayed in his time zone Central Time (US & Canada), and User B will see all the time in London.

Thanks all.

4

2 回答 2

3

controllers/application.rb

before_filter :set_user_time_zone

private

def set_user_time_zone
  Time.zone = current_user.time_zone if logged_in?
end

来自railscast

于 2013-07-31T11:14:24.727 回答
2

首先,您需要在 users 表中添加一列,以保留该用户的选定时区(user.timezone 应该没问题)。在表格中,您需要使用 ActiveSupport#time_zone_select来允许用户选择他们想要的时区。

最后,您需要 ApplicationController 中的前置过滤器将当前会话的时区设置为用户的特定时区。

以下是迁移、部分视图和应用程序控制器过滤器的要点:

https://gist.github.com/eladmeidar/6121183

于 2013-07-31T11:16:17.467 回答