2012-05-09 49 views
11

说我有被约束到特定子域以下途径:包括在Rails的URL帮手约束路由子域

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都对当前的子域返回的URL:“HTTP :// current-subdomain .lvh.me /“而不是特定于资源的子域。 我想root_url返回“HTTP:// WWW .lvh.me /”和backend_root_url返回的“http:// 管理 .lvh.me /”(行为应该是下的所有资源相同子域)。

我试图通过设置在各个地方的网址选项,一个是url_options在应用控制器来完成这个在轨道3.2:

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

也许我需要手动重写URL佣工?我将如何处理(访问路线等)?

编辑:我能够使用root_url(:subdomain =>“admin”)返回“http:// admin .lvh.me /”而不管当前子域是否得到正确的结果。不过,我宁愿不必在整个代码中指定。

回答

9

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

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 
+0

这很好用!我碰到的一个问题是,只有当您的基本域不包含子域名时才能使用。如果是这样,您需要将其包含为:host。或者您可以通过定义ApplicationController#default_url_options来设置:host来返回包含host的哈希。 – mltsy

+0

我收回它,即使这不能解决问题,如果你已经有一个主域名的子域名。我还没有想出一个办法,没有写你自己的帮手方法。 – mltsy