Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 711
SeanStove Avatar asked Dec 11 '25 02:12

SeanStove


1 Answers

What about using the path_prefix option instead

def default_url_options(options = {})
  { :path_prefix => I18n.locale }
end
like image 90
Carlos Ramirez III Avatar answered Dec 13 '25 22:12

Carlos Ramirez III



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!