Andy
Andy

Reputation: 541

How to get Rails root_path to redirect to /en/ locale?

I have an application that is available in EN and DE. Currently, when you enter the website www.example.com it does not redirect to default locale. Ideally, I would like root to immediately redirect so I get: www.example.com/en.

When I click a root_path link in the app, it goes to the frontpage including the locale www.example.org/en as expected.

Question: How do I ensure that users that enters www.example.com is redirected to www.example.com/en immediately?

Routes:

Rails.application.routes.draw do
  scope '(:locale)', locale: /en|de/ do
  root 'pages#landingpage'

Application controller:

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

def default_url_options(options = {})
  {locale: I18n.locale}
end

Upvotes: 1

Views: 1299

Answers (2)

Dmitriy Malyshev
Dmitriy Malyshev

Reputation: 41

For everyone who looking answer. In that case you can do

root to: redirect("/#{I18n.default_locale}"), as: :redirected_root

before your locale scope, then you will be redirected to default locale

root to: redirect("/#{I18n.default_locale}"), as: :redirected_root

scope '(:locale)', locale: /#{I18n.available_locales.join('|')}/ do
 root 'main#index'
end

Upvotes: 4

Ravi Prakash
Ravi Prakash

Reputation: 121

First of all please go through this Internationalization guidelines

Now try this in the routes:

scope "(/:locale)" {}

and use the config.default_locale option in the configuration. you can configure fallbacks for localization.

if you are using cookies to keep track of your locale, you can can skip the default_url_options, you will have to keep the unlocalized versions anyways for backward compatibility.

Upvotes: 0

Related Questions