0

I have a multi-language rails website created using the Rails I18n API with URLs like

"example.com/en/about" or "example.com/de/about" or "example.com/en/contact"

etc.

This works fine as is, but I would like that if a user goes to "example.com/about" (without the language part in the URL), he'd be redirected to the respective page in a default language, e.g. to "example.com/en/about"

My config/routes.rb looks like:

Example::Application.routes.draw do
  get '/:locale' => 'static_pages#home'
  scope "/:locale" do
    root "static_pages#home"
    match 'about', to: 'static_pages#about', via: 'get'
    match 'contact', to: 'contact#new', via: 'get'
  end
  resources "contact", only: [:new, :create]
end

I could redirect the URL on the server (apache) level, but I'd prefer to do this in rails.

user1583209
  • 1,637
  • 3
  • 24
  • 42

1 Answers1

0

you can do something like that in your ROUTES

Rails.application.routes.draw do
  scope "(:locale)", locale: /en|es/ do


  root                'static_pages#home'
  get 'static_pages' => 'static_pages#home'
  get '/:locale' => 'static_pages#home'
  get    'help'    => 'static_pages#help'
  get    'about'   => 'static_pages#about'
  get    'contact' => 'static_pages#contact'
  get    'signup'  => 'users#new'
  get    'login'   => 'sessions#new'
  post   'login'   => 'sessions#create'
  delete 'logout'  => 'sessions#destroy'
  end

And in your ApplicationController

    before_action :set_locale

  def set_locale
    if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
      cookies['locale'] = { :value => params[:locale], :expires => 1.year.from_now }
      I18n.locale = params[:locale].to_sym
    elsif cookies['locale'] && I18n.available_locales.include?(cookies['locale'].to_sym)
      I18n.locale = cookies['locale'].to_sym
    end
  end

  protect_from_forgery

    def default_url_options(options={})
    logger.debug "default_url_options is passed options: #{options.inspect}\n"
    { :locale => I18n.locale }
     end

  def extract_locale_from_tld
    parsed_locale = request.host.split('.').last
    I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
  end