Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes with optional scope ":locale"

I'm working on a Rails 3.1 app and I'd like to set specific routes for the different languages the app is going to support.

/es/countries
/de/countries
…

For the default language ('en'), I don't want the locale to be displayed in the url.

/countries

Here is the route definition I've set.

scope "(:locale)", :locale => /es|de/ do
   resources :countries
end

It works great, until I try to use a path helper with 'en' as the locale.

In the console :

app.countries_path(:locale => 'fr')
 => "/fr/countries" 

app.countries_path(:locale => 'en')
 => "/countries?locale=en" 

I don't want the "?locale=en".

Is there a way to tell rails that with an 'en' locale, the locale param should not be added to the url?

Thanks

like image 473
jlfenaux Avatar asked Nov 22 '11 09:11

jlfenaux


3 Answers

This SHOULD be a better solution:

In your routes.rb,

scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/, defaults: {locale: "en"} do

As MegaTux said, set defaults: {locale: "en"} in the scope.

The advantage: The jlfenaux solution works in most contexts, but not all. In certain contexts (like basically anything outside of your main controllers and views), the path helpers will get confused and put the object or object.id in the locale parameter, which will cause errors. You'll find yourself putting locale: nil in lots of path helpers to avoid those errors.

The possible problem: It seems that defaults: {locale: "en"} always overrides any other value you pass in for locale. The option is named default, so I'd expect it to assign locale to 'en' only when there's no value already, but that's not what happens. Anyone else experiencing this?

like image 110
Arcolye Avatar answered Nov 17 '22 01:11

Arcolye


I finally figured out how to do it easily. You just have to set the default_url_options in the app controller as below.

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

This way, you are sure the locale isn't sent to the path helpers.

like image 21
jlfenaux Avatar answered Nov 17 '22 01:11

jlfenaux


If you don't want the query string you don't have to pass it to the helper:

1.9.2 (main):0 > app.countries_path(:locale=>:de)
=> "/de/countries"
1.9.2 (main):0 > app.countries_path
=> "/countries"
1.9.2 (main):0 > app.countries_path(:locale=>:en)
=> "/countries?locale=en"
1.9.2 (main):0 > app.countries_path
=> "/countries"
1.9.2 (main):0 > app.countries_path(:locale=>nil)
=> "/countries"
like image 3
lucapette Avatar answered Nov 17 '22 01:11

lucapette