Rails: 如何路由到特定域

Rails: How to route to a specific domain

我定义了以下路线:

constraints( subdomain: "abc" ) do
    resources :sites do
        resources :pages
    end
    resources :domains
end

所以我可以像这样访问页面:abc.example.com/sites/1/pages/2

我想路由 PagesControllershow 操作可以像这样访问:a-different-domain.com/2

我有很多域,一个域可以有很多页。域有 domain 列。这是我认为可行的方法:

%w(domains).each do |d|
    constraints( host: d.domain ) do
        get "/*structure" => "pages/dashboard/sites/pages#show"
    end
end

我收到以下错误:

undefined method `domain' for "domains":String (NoMethodError)

如何使用 Rails 做到这一点?

您的代码存在问题,%w(domains)["domains"]

你可以这样做:

# routes.rb
Domain.find_each do |d|
  constraints(subdomain: d.domain) do
    get "/*structure" => "pages/dashboard/sites/pages#show"
  end
end

更多信息:http://edgeguides.rubyonrails.org/routing.html#request-based-constraints