V
V
V2015-03-26 01:28:15
Ruby on Rails
V, 2015-03-26 01:28:15

How to change user language in Rails?

I have a User model with a language attribute. I want the language to be automatically determined by the browser's Accept Header when visiting the site and this value would be written to the language attribute. For these purposes, I use the http_accept_language gem. Then there is a button "change language" from English to Russian and vice versa. Accordingly, the value of the attribute should change. The fact is that the language of the site changes, but is saved only in cookies, and the value of the language attribute remains nil.
application_controller.rb (language automatically detected and written to attribute)

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 (change language and write to attribute)
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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2015-03-26
@fuCtor

I'm not sure, but try rewriting it like this:

locale = params[:locale].to_sym
locale = nil unless I18n.available_locales.include?(locale)
cookies.permanent[:locale] = locale 
current_user.update(language: locale )

I also recommend putting:
gem 'better_errors'
gem 'binding_of_caller'
Helps when debugging to throw an exception in the right place and see what is happening there in the browser.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question