2012-05-09 45 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