从 Rails 中的子域中排除所有其他资源

Yuv*_*rmi 5 ruby-on-rails rails-routing ruby-on-rails-4

我有一个 Rails 4.0 应用程序,它允许用户通过子域访问博客。我的路线目前是这样的:

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

resources :foobars
Run Code Online (Sandbox Code Playgroud)

现在,当我导航到somesubdomain.example.com我确实像预期的那样show采取blogs控制器动作的动作时。

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

但是,我只得到了一个我不想要的行为:当我导航到 时somesubdomain.example.com/foobars,我仍然可以访问控制器的index操作foobars

有没有办法限制或排除我没有特别允许用于特定子域的所有资源(即,somesubdomain.example.com/foobars除非另有说明,否则将不起作用)。

谢谢!

ben*_*phw 2

如果您需要定义一个特定的子域以从一组路由中排除,您可以简单地执行此操作(使用负向前看正则表达式):

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

或者类似地,要定义一个特定的子域以包含一组路由,您可以这样做:

  # only for subdomain matching 'somesubdomain'
  constrain :subdomain => /^somesubdomain/ do
    root to: 'blog#show' 
    resources :foobars
  end
Run Code Online (Sandbox Code Playgroud)

另一种方法是在类(或模块)中定义约束匹配,然后将所有路由包装在constraints块中:

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
Run Code Online (Sandbox Code Playgroud)