Rails route clash when using scopes and localization / i18n
In ord开发者_高级运维er to internationalize my app I would like to have named routes like 'hello_path' automatically translated to '/en/hello' or '/fr/bonjour" depending on the current I18n.locale. But I encounter a problem (name clash?):
My routes are:
LostInTranslation::Application.routes.draw do
root :to => 'home#index'
scope '/:locale' do
constraints :locale => 'fr' do
get 'bonjour' => 'home#hello', :as => 'hello'
end
constraints :locale => 'en' do
get 'hello' => 'home#hello', :as => 'hello'
end
end
end
And in the ApplicationController I set the locale and pass it to the default url options:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale
private
def default_url_options(options={})
options.merge({ :locale => I18n.locale })
end
def set_locale
if params[:locale] and I18n.available_locales.include?(params[:locale].to_sym)
I18n.locale = params[:locale]
else
I18n.locale = I18n.default_locale
end
end
end
But when in a view I use <%= link_to t('hello'), hello_path %> I get this error:
No route matches {:controller=>"home", :locale=>:fr, :action=>"hello"}
Yet rake routes says it is declared:
root / {:action=>"index", :controller=>"home"}
hello GET /:locale/bonjour(.:format) {:locale=>"fr", :action=>"hello", :controller=>"home"}
hello GET /:locale/hello(.:format) {:locale=>"en", :action=>"hello", :controller=>"home"}
Would you have any clue about why it's not working or another way to achieve this? I am aware of the i18n_routing gem, but it works by declaring localized routes with different names (en_hello and fr_hello in this example).
Thanks!
I've no experience with the I18n_routing gem but would imagine it accepts the non-localized route and translates it for you; for example you supply hello_path and it does the rest.
You should have a default language which isn't namespaced
google.com # english default locale
google.com/es # spanish
rather than
google.com/en # english
google.com/es # spanish
google.com # nothing here
You should check out the translate_routes gem which has default locales and which I've used without any problems. https://github.com/raul/translate_routes
精彩评论