Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
909 views
in Technique[技术] by (71.8m points)

url routing - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...