Ruby on rails 多语言路由-当url\u为生成路径时,未考虑高级约束
我在rails 3.2中有一个多语言站点,它有一些特定于语言的路径映射到同一个操作。比如: 对于mydomain.frRuby on rails 多语言路由-当url\u为生成路径时,未考虑高级约束,ruby-on-rails,rails-routing,Ruby On Rails,Rails Routing,我在rails 3.2中有一个多语言站点,它有一些特定于语言的路径映射到同一个操作。比如: 对于mydomain.fr match "/bonjour_monde" => 'foo#bar' 对于mydomain.de match "/hallo_welt" => 'foo#bar' 为了解决这个问题,我在声明路由时使用了一个高级约束: Application.routes.draw do constraints(SiteInitializer.for_country("fr
match "/bonjour_monde" => 'foo#bar'
对于mydomain.de
match "/hallo_welt" => 'foo#bar'
为了解决这个问题,我在声明路由时使用了一个高级约束:
Application.routes.draw do
constraints(SiteInitializer.for_country("fr")) do
match "/bonjour_monde" => 'foo#bar'
end
constraints(SiteInitializer.for_country("de")) do
match "/hallo_welt" => 'foo#bar'
end
end
其中SiteInitializer只是一个响应匹配的类?方法并确定请求是否针对正确的域。这实际上只是演示我的设置的伪代码
class SiteInitializer
def initialize(country_code)
@country_code = country_code
end
def self.for_country(country_code)
new(country_code)
end
def matches?(request)
# based on the request, decide if this route should be declared
decide_which_country_code_from_request(request) == @country_code
end
end
这个很好用。当请求mysite.fr/bonjour\u monde时,应用程序将正确发送,路径仅绑定到其特定域
mysite.fr/bonjour_monde => HTTP 200
mysite.fr/hallo_welt => HTTP 404
mysite.de/bonjour_monde => HTTP 404
mysite.de/hallo_welt => HTTP 200
现在,一切都很好,除非您开始为(:controller=>'foo',:action=>'bar')使用url_之类的东西。如果执行此操作,则不会考虑约束。这导致从rails(旅程类)生成的路径是任意的
如果我在任何视图中的某处使用url_,比如
url_for(:controller => 'foo', :action => 'bar')
rails将选择任何与控制器操作匹配的任意声明路由,可能是第一个声明的路由,跳过以检查任何高级约束
如果用户访问mysite.de/hallo_welt,并且视图执行以下操作:
= url_for(:controller => 'foo', :action => 'bar', :page => '2')
输出可能是
mysite.de/bonjour_monde?page=2
^
wrong language
实际上,我并没有在代码中专门使用url_,但一些gem(如kaminari(paginator))会这样做,这就是为什么在生成路径时,您可能会限制使用使用标准帮助器方法的库
现在,我不确定Traveley类是否应该考虑请求上下文。但是你会如何处理这种问题呢