有没有办法设置语言环境并在请求之间设置它而不使用应用程序控制器中的before_action / before_filter?
我正试图避免目前的解决方案:
class ApplicationController < ActionController::Base
before_action :set_locale
def set_locale
I18n.locale = current_user.locale if current_user
end
end
class LocaleController < ApplicationController
skip_authorization_check
def index
locale = params[:locale]
raise 'Unsupported locale' unless ['en', 'pt'].include?(locale)
error_message = "Could not set locale" unless current_user.update_column(:locale, locale)
I18n.locale = current_user.locale if error_message.nil?
redirect_to :back, :alert => error_message
end
end
答案 0 :(得分:1)
您应该只使用
class ApplicationController < ActionController::Base
catrr_accesor :locale_set
before_action :set_locale :if => lambda {|c| locale_set}
def set_locale
I18n.locale = current_user.locale if current_user
ApplicationController.locale_set = true
end
end
从代码中可以看出,其他控制器继承了这一点。
也许你想做类似的事情:
def set_locale
I18n.locale = user_signed_in? ? current_user.locale.to_sym : (params[:local] || I18n.default_locale)
end
为了摆脱设计,你可以用这样的东西结束:
# get locale of user
def after_sign_in_path_for(resource_or_scope)
if resource_or_scope.is_a?(User) && resource_or_scope.locale != I18n.locale
I18n.locale = resource_or_scope.locale.to_sym || I18n.default_locale
end
session[:previous_url] || root_path
end