If you follow the I18N Rails Guide, all generated links contain the locale parameter (localhost/en/about, localhost/fr/about). This is because we use the method defaul
I know it's not exactly your question but...
I prefer the other way for internationalisations: Setting the Locale from the Domain Name
Ex: mysite.com/about, mysite.fr/about
For me it's the best way, but you need to buy all domains.
The selected answer is totally right on and provides everything you need to redirect URLs without a locale to your default locale, but I wanted to do something a bit more and figured I'd share it with you.
I wanted to avoid having to use the default locale at all, that is to say
mysite.com/en/page
should be the same asmysite.com/page
AND all links when viewing from the default locale should NOT include the locale, meaning mysite.com should have links that do not include the default locale (en) in them. Instead of mysite.com
linking to
mysite.com/en/page
it should link tomysite.com/page
I achieved this via the following edits to default_url_options
:
def default_url_options(options={})
{ :locale => ((I18n.locale == I18n.default_locale) ? nil : I18n.locale) }
end
You must define config.i18n.default_locale
in config/application.rb for this to work. You can also assign fallbacks for unsupported locales via config.i18n.fallbacks = [ :en ]
where that array is a priority-ordered list of languages to fallback to.
Ok I understand much better. Indeed, you almost did it.
You just need a very useful operator in Ruby: ||
If the first value exists, it's used, otherwise the second argument is taken into account.
def set_locale
I18n.locale = params[:locale] || :en
end
Rails 4 + https://github.com/svenfuchs/routing-filter
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def default_url_options(options = {})
(I18n.locale.to_sym.eql?(I18n.default_locale.to_sym) ? {} : {locale: I18n.locale}).merge options
end