This is how I did it in one of Rails 4 applications:
in config/routes.rb:
Rails.application.routes.draw do
scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do
# rest of your routes here
# for example:
resources :projects
end
end
make sure in config/environments/production.rb this line is uncommented:
config.i18n.fallbacks = true
If you wish to have a default_locale
setup other than :en
, then in config/application.rb, uncomment this line:
config.i18n.default_locale = :de # and then :de will be used as default locale
Now, last part of your setup, add this method in ApplicationController
:
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_locale
private
def set_locale
I18n.locale = params[:locale] || session[:locale] || I18n.default_locale
session[:locale] = I18n.locale
end
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}
"
{ locale: I18n.locale }
end
end
Now, your application can be accessed as: http://localhost:3000/en/projects
, http://localhost:3000/fr/projects
, or http://localhost:3000/projects
. The last one http://localhost:3000/projects
will use :en
as its default locale(unless you make that change in application.rb).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…