Ruby on Rails Routes with Locales

I use this guide: http://edgeguides.rubyonrails.org/i18n.html

What I would like:

/aboutgoes into pages#aboutdefault by default en.

/en/aboutgoes into pages#aboutwith locale en.

/es/aboutgoes into pages#aboutwith locale es.

What I get:

/aboutgoes into root_pathwith locale about.

/en/aboutgoes into pages#aboutwith locale en.

/es/aboutgoes into pages#aboutwith locale es.

Here is the code:

# config/routes.rb
match '/:locale' => 'pages#news'

scope "(:locale)", :locale => /en|es/ do
  match '/abcd' => 'pages#abcd'
  match '/plan' => 'pages#plan'
  match '/about' => 'pages#about'
  match '/history' => 'pages#history'
  match '/projects' => 'pages#projects'
  match '/donate' => 'pages#donate'
  match '/opportunities' => 'pages#opportunities'
  match '/board' => 'pages#board'
end

root :to => "pages#news"

# app/controller/application_controller.rb
before_filter :set_locale

def set_locale
  # if params[:locale] is nil then I18n.default_locale will be used
  I18n.locale = params[:locale]
end

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

If I read the manual correctly, section 2.5 says that I should have access to /aboutand download it by default.

From 2.5:

# config/routes.rb
scope "(:locale)", :locale => /en|nl/ do
  resources :books
end

With this approach, you will not get a routing error when accessing your resources such as http: // localhost: 3001 / books without a locale. This is useful when you want to use the default locale when one is not specified.

+5
3

.rb - ,

match '/:locale' => 'pages#news'

, .

+6

:

Possible_locales = /en|es/

match '/:locale' => 'pages#news', :locale => Possible_locales

scope "(:locale)", :locale => Possible_locales do
   ...
end

.

+4

This blogpost actually explains this in great detail (Rails 4):

What I was looking for when nothing works

http://dhampik.com/blog/rails-routes-tricks-with-locales

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

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

  get "/*path", to: redirect("/#{I18n.default_locale}/%{path}", status: 302), constraints: {path: /(?!(#{I18n.available_locales.join("|")})\/).*/}, format: false

Default lang redirection from root and more.

+1
source

All Articles