Rails routes with optional scope “:locale”

前端 未结 6 1204
清歌不尽
清歌不尽 2020-12-06 06:08

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
…
<         


        
6条回答
  •  时光取名叫无心
    2020-12-06 06:16

    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?

提交回复
热议问题