2011-05-07 57 views
6

在我的routes.rb文件中,我想使用rails3中的子域约束功能,但是我想从捕获所有路由中排除某些域。我不想在特定子域中拥有某个控制器。这样做最好的做法是什么?子域约束和排除某些子域

# this subdomain i dont want all of the catch all routes 
constraints :subdomain => "signup" do 
    resources :users 
end 

# here I want to catch all but exclude the "signup" subdomain 
constraints :subdomain => /.+/ do 
    resources :cars 
    resources :stations 
end 

回答

11

您可以在约束正规表达式中使用negative lookahead来排除某些域。

constrain :subdomain => /^(?!login|signup)(\w+)/ do 
    resources :whatever 
end 

尝试了这一点上Rubular

+1

谢谢你帮助我使用这种技术。我自己修改它以进一步限制正则表达式与之后的第一位和附加字符不匹配。 – 2011-05-08 11:13:09

+1

@edgerunner感谢您的Rubular链接! – scarver2 2013-07-18 19:14:16

3

这是我来解决。

constrain :subdomain => /^(?!signup\b|api\b)(\w+)/ do 
    resources :whatever 
end 

它将匹配apiapis

+0

它确实排除'api'而不是'apis',但请记住它也会排除'api-foo'。使用'\ Z'(字符串结尾)而不是'\ b'(字面边界,正如George清楚地知道的)将不再排除'api-foo'。 (当然,这一切都取决于你为什么要排除这些字符串,但更多的选择更好,我想!) – 2011-07-15 20:40:06

1

使用负先行通过edgerunner &的建议乔治是伟大的。

基本格局将是:

constrain :subdomain => /^(?!signup\Z|api\Z)(\w+)/ do 
    resources :whatever 
end 

这是同乔治的建议,但我改变了\b\Z - 从文字边界的输入字符串本身的结尾变化(如备注在我对乔治的回答的评论中)。

这里有一堆的测试案例示出差异:,我只是想到了另外一个办法,可能取决于你想要什么工作

irb(main):001:0> re = /^(?!www\b)(\w+)/ 
=> /^(?!www\b)(\w+)/ 
irb(main):003:0> re =~ "www" 
=> nil 
irb(main):004:0> re =~ "wwwi" 
=> 0 
irb(main):005:0> re =~ "iwwwi" 
=> 0 
irb(main):006:0> re =~ "ww-i" 
=> 0 
irb(main):007:0> re =~ "www-x" 
=> nil 
irb(main):009:0> re2 = /^(?!www\Z)(\w+)/ 
=> /^(?!www\Z)(\w+)/ 
irb(main):010:0> re2 =~ "www" 
=> nil 
irb(main):011:0> re2 =~ "wwwi" 
=> 0 
irb(main):012:0> re2 =~ "ww" 
=> 0 
irb(main):013:0> re2 =~ "www-x" 
=> 0 
1

重温这个老问题...

Rails的路由器尝试按照指定的顺序将请求匹配到路由。如果发现匹配,则其余路线是而不是检查。在您保留的子域块中,您可以将glob up all remaining routes发送到错误页面。

constraints :subdomain => "signup" do 
    resources :users 
    # if anything else comes through the signup subdomain, the line below catches it 
    route "/*glob", :to => "errors#404" 
end 

# these are not checked at all if the subdomain is 'signup' 
resources :cars 
resources :stations