好的,我已经设法解决了这个问题:
默认情况下,没有办法在Rails中这样做(至少,还没有).我需要安装Sven Fuchs的路由过滤器,而不是使用命名空间和默认值.
安装插件后,我将以下文件添加到我的lib目录:
require 'routing_filter/base' module RoutingFilter class Locale < Base # remove the locale from the beginning of the path, pass the path # to the given block and set it to the resulting params hash def around_recognize(path, env, &block) locale = nil path.sub! %r(^/([a-zA-Z]{2})(?=/|$)) do locale = $1; '' end returning yield do |params| params[:locale] = locale || 'en' end end def around_generate(*args, &block) locale = args.extract_options!.delete(:locale) || 'en' returning yield do |result| if locale != 'en' result.sub!(%r(^(http.?://[^/]*)?(.*))){ "#{$1}/#{locale}#{$2}" } end end end end end
我将此行添加到routes.rb:
map.filter 'locale'
这基本上填充了插件生成的前后挂钩,它包裹了rails路由.
当识别出一个url,并且在Rails开始对它做任何事情之前,会调用around_recognize方法.这将提取一个代表语言环境的双字母代码,并在params中传递它,如果没有指定语言环境,则默认为'en'.
同样,当生成url时,locale参数将被推送到左侧的URL中.
这给了我以下网址和映射:
/ => :locale => 'en' /en => :locale => 'en' /fr => :locale => 'fr'
所有现有的url助手都像以前一样工作,唯一的区别是除非指定了语言环境,否则它将被保留:
home_path => / home_path(:locale => 'en') => / home_path(:locale => 'fr') => /fr