-1

有没有办法设置区域设置并在请求之间保持设置而不在应用程序控制器中使用 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
4

1 回答 1

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
于 2013-10-03T14:47:51.887 回答