【问题标题】:Rails. Set default timezone when current_user loaded导轨。加载 current_user 时设置默认时区
【发布时间】:2015-02-12 01:23:42
【问题描述】:

我想在 current_user (Devise) 初始化时更改应用程序时区,如下所示:

    Time.zone = current_user.settings(:main).time_zone

将此代码放在应用程序中的最佳位置是什么(应用程序控制器,before_filter 不是解决方案)?

【问题讨论】:

  • 为什么ApplicationController 不是解决方案?这将是我的建议......
  • 同意@dgilperez。 ApplicationController'before_filter 是解决方案。
  • 我不认为更改应用时区是正确的方法。如果用户更改时区怎么办? (或者它会随着夏令时改变自己?)

标签: ruby-on-rails ruby devise


【解决方案1】:

我认为这里最安全的方法是像这样使用 around_action,确保指定您希望在哪个操作上发生这种情况:

class SomeController < ApplicationController
    around_action :set_time_zone, only: :show

    private

    def set_time_zone
       if current_user
         Time.zone = current_user.settings(:main).time_zone 
       end
       yield         
    end
end

【讨论】:

  • ApplicationController 的问题是其他一些控制器无权访问 current_user(如 API 控制器),但“if current_user”应该可以解决这个问题。 :) 非常感谢您的建议!
猜你喜欢
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 2012-12-21
  • 2011-11-21
  • 2012-03-29
  • 2011-07-01
  • 2018-07-21
相关资源
最近更新 更多