2015-02-11 44 views
0

我想更改應用程序時區時,CURRENT_USER(設計)被初始化,這樣的:Rails。 CURRENT_USER加載時設置默認時區

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

什麼是應用最好的地方,把這個代碼在(應用程序控制器,before_filter不是解決方案)?

+0

爲什麼''ApplicationController''是不是一個解決方案?這將是我的建議... – dgilperez 2015-02-11 13:53:01

+0

Aggree與@dgilperez。 'ApplicationController'''before_filter'是解決方案。 – pierallard 2015-02-11 14:27:11

+0

我不相信更改應用程序時區是正確的方法。如果用戶更改時區怎麼辦? (或者它改變了夏令時? – 2015-02-11 15:28:39

回答

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 
+0

ApplicationController的問題是其他一些控制器沒有權限訪問current_user(比如API控制器),但是「如果current_user」應該解決這個問題。 :)非常感謝你的建議! – Serge 2015-02-12 01:39:27

+0

沒問題Serge !,很高興幫助,請標記答案,如果接受:) – DevDude 2015-02-12 16:54:13