2014-09-04 60 views
4

添加子域名我非常新的鐵軌和我的大多數知識依賴於教程:)針對不同用戶類型

於是,我跟着這個http://www.railstutorial.org教程,創造了真正的好網站,但現在我遇到一個問題。對於我的用戶,我在我的數據庫中有一個特殊的列,顯示他是哪種類型的用戶。例如,如果用戶是學生,我有專欄'學生',如果他不是,那麼'真',而'假'。

現在我想爲學生創建一個子域名。所以,當學生想要註冊或登錄時,他會轉到www.student.mysite.com而不是www.mysite.com。

我該如何做到這一點?

謝謝:)

回答

2

有許多方法可以做到這一點,特別是你感興趣的關於查找multi-tenancy到軌

-

多租戶

雖然多租戶通常是具有多個數據庫/資產(每個用戶一個)的定義,但是,因爲它很難得到這個工作克護欄(這是我們目前正在處理),則可以使用原理與數據

的一個堆疊

有關於如何使用Rails這裏實現這個幾個教程:

雖然這不是直接關係到你的問題,大部分的 通常基於「多租戶」問題,「我怎麼了我的用戶創建不同的子域」

-

子域

Rails子域的基礎是捕獲請求並將其路由到正確的控制器。我們已經成功地實現,使用以下設置:

#config/routes.rb 
constraints Subdomain do #-> lib/subdomain.rb & http://railscasts.com/episodes/221-subdomains-in-rails-3 

    #Account 
    namespace :accounts, path: "" do #=> http://[account].domain.com/.... 

     #Index 
     root to: "application#show" 

    end 
end 

#lib/subdomain.rb 
class Subdomain 
    def self.matches?(request) 
    request.subdomain.present? && request.subdomain != 'www' 
    end 
end 

這會給你做以下的能力:

#app/controllers/accounts/application_controller.rb 
class Account::ApplicationController < ActionController::Base 
    before_action :set_account 

    def show 
     #@account set before_action. If not found, raises "not found" exception ;) 
    end 

    private 

    #Params from Subdomain 
    def set_account 
     params[:id] ||= request.subdomains.first unless request.subdomains.blank? 
     @account = Account.find params[:id] 
    end 
end 

理想情況下,我們很樂意在中間件來處理這個問題,但就目前而言,這就是我們所擁有的!

這會給你打電話給你從@account變量需要數據的能力:

#app/views/accounts/application/show.html.erb 
<%= @account.name %> 
+0

謝謝。+1,但我仍然不明白如何根據用戶的個人資料將用戶重定向到特定的域。所以,如果他是一名學生,我想重定向到student.myapp.com。 – user3304086 2014-09-10 22:32:55