为了国际化我的应用程序,我想有命名的路由,如'hello_path'自动翻译为'/en/hello'或'/fr/bonjour"取决于当前的I18n.locale。但是我遇到了一个问题(名称冲突?):
我的路由是:
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
在ApplicationController中,我设置了区域设置,并将其传递给默认的url选项:
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
但是当我在视图中使用<%= link_to t('hello')时,hello_path %>我得到这个错误:
No route matches {:controller=>"home", :locale=>:fr, :action=>"hello"}
然而rake路由说它被声明了:
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"}
你是否有任何线索,为什么它不工作或其他方法来实现这一点?我知道i18n_routing gem,但它通过声明具有不同名称的本地化路由(在本例中为en_hello和fr_hello)来工作。
谢谢!
我没有使用过I18n_routing gem的经验,但可以想象它会接受非本地化路由并为你翻译它;例如,您提供hello_path,它会完成其余的工作。
你应该有一个没有命名空间的默认语言
google.com # english default locale
google.com/es # spanish
而不是
google.com/en # english
google.com/es # spanish
google.com # nothing here
你应该看看translate_routes gem,它有默认的区域设置,我使用它没有任何问题。https://github.com/raul/translate_routes