SeanStove
SeanStove

Reputation: 71

Rails Internationalization (I18n): locale in the url

I'm new to rails (using 3.2.1) and I was following the i18n-guide on rails guides.

I'm having problems with this section:

You probably want URLs to look like this: www.example.com/en/books (which loads the English locale) and www.example.com/nl/books (which loads the Netherlands locale). This is achievable with the “over-riding default_url_options” strategy from above: you just have to set up your routes with path_prefix option in 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 type an url in the browser (f.e. 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

Upvotes: 3

Views: 2797

Answers (2)

SeanStove
SeanStove

Reputation: 71

I ended up using the rails-translate-routes gem.

It gave me the expected result + it's possible to translate the routes which is a great surplus.

Upvotes: 0

Carlos Ramirez III
Carlos Ramirez III

Reputation: 7434

What about using the path_prefix option instead

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

Upvotes: 1

Related Questions