我有一个带有属性语言的模型用户。当用户访问站点时,应通过浏览器的Accept Header语言自动检查语言环境,并且应将此语言环境设置为语言属性。我使用gem' http_accept_language'。我还有按钮"更改语言",这应该改变用户的语言。现在网站的语言发生了变化,但只保存在cookie中,语言属性等于nil ..
application_controller.rb(自动检查Accept Header的语言并将其设置为用户的语言)
**class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :require_login, :set_locale
include HttpAcceptLanguage::AutoLocale
private
def not_authenticated
redirect_to login_path, alert: "Пожалуйста, войдите на сайт"
end
def set_locale
if params[:locale].present?
locale = params[:locale].to_sym
cookies.permanent[:locale] = I18n.available_locales.include?(locale) ? locale : nil
current_user.update(language: cookies.permanent[:locale])
end
I18n.locale = cookies[:locale]
end
end**
settings_controller.rb(更改语言)
class SettingsController < ApplicationController
def change_locale
l = params[:locale].to_s.strip.to_sym
l = I18n.default_locale unless I18n.available_locales.include?(l)
u = current_user
u.update(language: I18n.locale.to_s)
redirect_to request.referer || root_url
end
end