Search code examples
ruby-on-railsrouteslocale

Defaulting locale if locale missing in Rails


I have my web app translated into english and croatian. English being set as default locale in my config/application.rb and enabled all fallbacks:

config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :en
config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)
I18n.enforce_available_locales = true
config.i18n.fallbacks = true
config.i18n.fallbacks = [:en]
config.i18n.fallbacks = {'es' => 'en', 'fr' => 'en', 'de' => 'en'}

My config/routes.rb are defined like this:

scope "(:locale)", :locale => /en|hr/ do
  root :to => 'static_pages#home'
  match 'signin', to: 'sessions#new', via: 'get'
  match 'signout', to: 'sessions#destroy', via: 'delete'
  match '/signup', to: 'users#new', via: 'get'
  match '/about',   to: 'static_pages#about',   via: 'get'
  resources :sessions, only: [:new, :create, :destroy]
  resources :relationships, only: [:create, :destroy]

  resources :users do
    member do
      get :following, :followers
    end
  end

end

Everything works perfect when a user is using the app and switches between the languages, but if a user goes to the url and types in for example "es" instead of "en" or "hr" I get a routing error page with the error description: No route matches [GET] "/es/signin"

How can I make it fallback to english locale, if the whole .yml file in the locales folder is missing?


Solution

  • Add es or any other locale to your regex in config/routes.rb: :locale => /en|hr|es/. Anything except those values will cause routing error.