路由:无法获取默认范围(:locale)以使用user_path(id),始终必须明确提交区域设置

我已经对这个话题进行了一些研究,但我似乎无法弄明白。

我已经按照官方指南设置了I18n,但是我没有正确设置默认语言环境(当没有指定明确的语言环境时)。

# routes.rb require 'sidekiq/web' Iq::Application.routes.draw do scope "(:locale)", locale: /de|en/ do # ... end end # application_controller.rb class ApplicationController  I18n.locale }) end end 

在OS X控制台中:

 $ rake routes | grep user ... user GET (/:locale)/users/:id(.:format) users#show {:locale=>/de|en/} ... 

在Rails控制台中:

 $ Rails c $ app.users_path => "/users" app.users_path locale: :de => "/de/users" $ app.user_path User.first, locale: :de => "/de/users/509fc01d77bb1e6a050000a0" $ app.user_path User.first ActionController::RoutingError: No route matches {:action=>"show", :controller=>"users", :locale=>#} from /Users/josh/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.2.8/lib/action_dispatch/routing/route_set.rb:532:in `raise_routing_error' 

为什么这不起作用? 我忘记了什么?

非常感谢你的帮助,乔希

一位同事A对此进行了调查,并决定不将(:locale)放入括号中。 另一位同事B提到,他把它放在括号中以便我们的测试工作,我们不想在调用url helper方法时明确指定语言环境。

同事A提到,当没有语言环境调用url helper方法时,应用程序本身会回退到上面提到的default_url_options方法。 这很好,因为除了root_path ,我们总是想要一个显式的语言集。

但是在测试中, default_url_options方法被忽略(我不确定这是一个bug还是一个特性,哈哈)。 所以必须做一些解决方法:

 # Fixes the missing default locale problem in request specs. # See http://www.ruby-forum.com/topic/3448797 class ActionView::TestCase::TestController def default_url_options(options={}) { :locale => I18n.default_locale } end end class ActionDispatch::Routing::RouteSet def default_url_options(options={}) { :locale => I18n.default_locale } end end # Fixes the missing default locale problem in controller specs # See http://www.ruby-forum.com/topic/3448797#1041659 class ActionController::TestCase module Behavior def process_with_default_locale(action, parameters = nil, session = nil, flash = nil, http_method = 'GET') parameters = { :locale => I18n.default_locale }.merge( parameters || {} ) process_without_default_locale(action, parameters, session, flash, http_method) end alias_method_chain :process, :default_locale end end module ActionDispatch::Assertions::RoutingAssertions def assert_recognizes_with_default_locale(expected_options, path, extras = {}, message=nil) expected_options = { :locale => I18n.default_locale.to_s }.merge(expected_options || {} ) assert_recognizes_without_default_locale(expected_options, path, extras, message) end alias_method_chain :assert_recognizes, :default_locale end 

把它放到你的spec_helper.rb文件中,你就可以使用你的控制器并请求规格了! 🙂

不过,在控制台中,这似乎没有办法:

 $ app.user_path User.first ActionController::RoutingError: No route matches...