2014-01-16 32 views
2

我有一个Rails 4.0应用程序,允许用户通过子域访问博客。我目前的路线是这样的:从Rails中的子域中排除所有其他资源

match '', to: 'blogs#show', via: [:get, :post], constraints: lambda { |r| r.subdomain.present? && r.subdomain != 'www' } 

resources :foobars 

现在,当我浏览到somesubdomain.example.com我确实带到blogs控制器动作的show作用,符合市场预期。

当我导航到example.com/foobars时,我可以按照预期访问foobars控制器的index操作。

不过,我只得到一个行为我不渴望: 当我浏览到somesubdomain.example.com/foobars,我仍然可以访问foobars控制器的index行动。

有没有办法限制或排除所有资源,我不特别允许特定的子域(即somesubdomain.example.com/foobars将不会工作,除非另有规定)。

谢谢!

回答

2

如果您需要定义一个特定子域排除从一组的路线,你可以简单地这样做的(使用负向前查找正则表达式):

# exclude all subdomains with 'www' 
    constrain :subdomain => /^(?!www)(\w+)/ do 
    root to: 'session#new' 
    resources :foobars 
    end 

或类似的,定义一个特定子域包括一组路线的你可以这样做:

# only for subdomain matching 'somesubdomain' 
    constrain :subdomain => /^somesubdomain/ do 
    root to: 'blog#show' 
    resources :foobars 
    end 

另一种方法是在一个类(或模块)中定义的约束匹配,然后换行的所有路由constraints block:

class WorldWideWebSubdomainConstraint 
    def self.matches?(request) 
    request.subdomain.present? && request.subdomain != 'www' 
    end 
end 

App::Application.routes.draw do 

    # All "www" requests handled here 
    constraints(WorldWideWebSubdomainConstraint.new) do 
    root to: 'session#new' 
    resources :foobars 
    end 

    # All non "www" requests handled here 
    root to: 'blogs#show', via: [:get, :post] 

end 
+0

谢谢。这正是我最终做的。 –