在Rails url helper中包含受约束路由的子域

时间:2012-05-09 02:10:37

标签: ruby-on-rails routes

假设我有以下限制在特定子域的路由:

App::Application.routes.draw do
  constraints :subdomain => "admin" do
    scope :module => "backend", :as => "backend" do
      resources :signups
      root :to => "signups#index"
    end
  end
  constraints :subdomain => "www" do
    resources :main
    root :to => "main#landing"
  end
end

我的问题是root_urlbackend_root_url都返回当前子域名的网址:“http:// current-subdomain .lvh.me /”而不是特定于资源的子域。 我希望root_url返回“http:// www .lvh.me /”和backend_root_url返回“http:// admin .lvh.me /“(子域下所有资源的行为应该相同)。

我试图在rails 3.2中通过在各个地方设置url选项来实现这一点,其中一个是应用程序控制器中的url_options:

class ApplicationController < ActionController::Base
  def url_options
    {host: "lvh.me", only_path: false}.merge(super)
  end
end

也许我需要手动覆盖网址助手?我该如何处理(访问路线等)?

编辑:我可以使用root_url(:subdomain =&gt;“admin”)获得正确的结果,该结果返回“http:// admin .lvh.me /”,无论当前的子域名。但是,我不希望在代码中指定这一点。

1 个答案:

答案 0 :(得分:10)

使用如下所示的“默认值”将使rails url helpers输出正确的子域。

App::Application.routes.draw do
  constraints :subdomain => "admin" do
    scope :module => "backend", :as => "backend" do
      defaults :subdomain => "admin" do
        resources :signups
        root :to => "signups#index", :subdomain => "admin"
      end
    end
  end

  constraints :subdomain => "www" do
    defaults :subdomain => "www" do
      resources :main
      root :to => "main#landing"
    end
  end
end
相关问题