Ruby on rails 在Ruby应用程序的时间戳上反映用户选择的时区

Ruby on rails 在Ruby应用程序的时间戳上反映用户选择的时区,ruby-on-rails,timezone,timestamp,Ruby On Rails,Timezone,Timestamp,我想根据用户选择的时区在ruby应用程序上制作每个时间戳。我对rails中的ruby还不熟悉,所以不知道怎么做 我让下拉列表出现,让用户从中选择时区 <%= time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.all, :default => "Beijing")%> “北京”)%%> 如何使时区的选择反映在所使用的所有时间戳上。在应用程序\u控制器中使用前过滤器。rb确保每个请求都调用此方法。每个请

我想根据用户选择的时区在ruby应用程序上制作每个时间戳。我对rails中的ruby还不熟悉,所以不知道怎么做

我让下拉列表出现,让用户从中选择时区

<%= time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.all, :default => "Beijing")%>
“北京”)%%>

如何使时区的选择反映在所使用的所有时间戳上。

应用程序\u控制器中使用
前过滤器
。rb
确保每个请求都调用此方法。每个请求的默认时区由
config.time\u zone
设置,因此您必须在每个请求上更新
time.zone
。看

要使用特定时区计算表达式,请使用
Time.use\u zone

Time.use_zone('Singapore') do
  Time.zone.parse(...) # returns a time in Singapore
end
更新:使用
会话
保存时区

# application_controller.rb
before_filter :set_user_timezone

def set_user_timezone
  Time.zone = session[:timezone] || 'Default timezone here'
end

# time_zone_controller.rb
def save_time_zone
  session[:timezone] = params[:timezone]
end

# routes
match 'save_time_zone' => 'time_zone#save_time_zone'

# js
$('#user_time_zone').change(function() {
  $.ajax({
    url: '/save_time_zone',
    data: { time_zone: $(this).val() }
  })
})

我得到了未定义的局部变量或方法“current\u user”用您用来获取当前登录用户的方法替换上面的
current\u user
。好吧……如果我没有任何用户登录呢??那我应该用什么?实际上,我的应用程序没有任何用户会话。我想使用这个时区实用程序,这样任何终端用户都可以看到他在时区中所做更改的时间戳。好的。我做出这个假设是因为您使用了上面的
:user
。如果没有任何用户,您可能可以使用会话来保存所选时区。如果你想这样做,我会更新我的答案。对不起,我没有提到……是的,请更新答案,因为我只想实现这一点
# application_controller.rb
before_filter :set_user_timezone

def set_user_timezone
  Time.zone = session[:timezone] || 'Default timezone here'
end

# time_zone_controller.rb
def save_time_zone
  session[:timezone] = params[:timezone]
end

# routes
match 'save_time_zone' => 'time_zone#save_time_zone'

# js
$('#user_time_zone').change(function() {
  $.ajax({
    url: '/save_time_zone',
    data: { time_zone: $(this).val() }
  })
})