Devise: fetch and set locale from User model

2019-08-06 15:54发布

问题:

I set the locale for every user in the User table. I followed these instructions to fetch the locale after the user logs in. It works until the user reloads the browser, then the standard locale (en) becomes active again. How can I keep the value of user.locale in the session? I'm using Rails_Admin, which means whilst I do have a User model, I don't have controller for the User model.

 # ApplicationController
 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
  end
  super
end 

回答1:

While putting it in the session is a valid answer, you can use the current_user method to get the user's locale (and keep your session a tad cleaner)

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale # get locale directly from the user model

  def set_locale
    I18n.locale = user_signed_in? ? current_user.locale.to_sym : I18n.default_locale
  end
end


回答2:

Managed to save it in the session and retrieve it from the session every time the user calls an action (before_filter in ApplicationController):

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale # get locale from session when user reloads the page

  # get locale of user
  def after_sign_in_path_for(resource_or_scope)
    if resource_or_scope.is_a?(User) && resource_or_scope.locale.to_sym !=  I18n.locale
      I18n.locale = resource_or_scope.locale.to_sym # no strings accepted
      session[:locale] = I18n.locale      
    end        
    super
  end

  def set_locale
    I18n.locale = session[:locale]
  end
end


回答3:

I added a string column to my User model called user_locale and then added code to the application controller. Allows the storage, default and locale use as a parameter.

migration:

class AddLocaleToUser < ActiveRecord::Migration
 def change
   add_column :users, :user_locale, :string
 end
end 

application_controller.rb:

before_action :set_locale

private 

def set_locale
 valid_locales=['en','es']

 if !params[:locale].nil? && valid_locales.include?(params[:locale]) 
   I18n.locale=params[:locale]
   current_user.update_attribute(:user_locale,I18n.locale) if user_signed_in?
 elsif user_signed_in? && valid_locales.include?(current_user.user_locale)
   I18n.locale=current_user.user_locale
 else
  I18n.locale=I18n.default_locale
 end
end