Rail Internationalization (I18n): Language in URL

I am new to rails (using 3.2.1) and I have been following the i18n-guide in guide rails .

I am having problems with this section:

The URLs are likely to look like this: www.example.com/en/books (which downloads English) and www.example.com/nl/books (which downloads the locale of the Netherlands). This is achieved using the "over-riding default_url_options" strategy above: you just have to configure routes using the path_prefix option this way

But when I use <% = products_path%> in my views, it returns: / products? locale = en and I want it to return / nl / products

When I enter the URL in the browser (e.g. localhost: 3000 / nl / products), the page displays the correct locale.

What am I missing?

Application controller:

class ApplicationController < ActionController::Base
  before_filter :set_locale

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

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

routes:

  scope "/:locale" do
    resources :products
  end

  match '/:locale' => 'products#index'

rake routes:

    products GET    /products(.:format)                  products#index
             POST   /products(.:format)                  products#create
 new_product GET    /products/new(.:format)              products#new
edit_product GET    /products/:id/edit(.:format)         products#edit
     product GET    /products/:id(.:format)              products#show
             PUT    /products/:id(.:format)              products#update
             DELETE /products/:id(.:format)              products#destroy
             GET    /:locale/products(.:format)          products#index
             POST   /:locale/products(.:format)          products#create
             GET    /:locale/products/new(.:format)      products#new
             GET    /:locale/products/:id/edit(.:format) products#edit
             GET    /:locale/products/:id(.:format)      products#show
             PUT    /:locale/products/:id(.:format)      products#update
             DELETE /:locale/products/:id(.:format)      products#destroy
                    /:locale(.:format)                   products#index
        root        /                                    products#index
+3
source share
2 answers

I ended up using rails-translate-routes gem .

This gave me the expected result + the ability to translate routes that are a big surplus.

0
source

How to use option path_prefixinstead

def default_url_options(options = {})
  { :path_prefix => I18n.locale }
end
+1
source

All Articles