-
-
Save francelwebdev/a407555fd308a893225170b9147d4a12 to your computer and use it in GitHub Desktop.
Ruby on Rails i18n: using user locale
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# db/migrates/*_add_locale_to_users.rb | |
class AddLocaleToUsers < ActiveRecord::Migration | |
def change | |
add_column :users, :locale, :string, default: "fr" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/application_controller.rb | |
class ApplicationController < ActionController::Base | |
protect_from_forgery with: :exception | |
before_action :set_current_user | |
before_action :set_locale | |
private | |
def set_current_user | |
if session[:user_id] | |
@current_user = User.find(session[:user_id]) | |
end | |
end | |
def set_locale | |
if @current_user.try(:locale) | |
I18n.locale = current_user.locale | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment