为不同的用户类型添加子域

时间:2014-09-04 00:16:30

标签: ruby-on-rails ruby-on-rails-4 subdomain

我是Rails的新手,我的大部分知识都取决于教程:)

所以,我按照这个http://www.railstutorial.org教程创建了非常好的网站,但现在我遇到了一个问题。对于我的用户,我的数据库中有一个特殊列,显示他是哪种类型的用户。例如,我有专栏'学生'这是真的'如果用户是学生并且“假”'如果他没有。

现在我想为学生创建一个子域名。因此,当学生想要注册或登录时,他将被转移到www.student.mysite.com而不是www.mysite.com。

我该如何实现?

谢谢:)

1 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点,特别是你有兴趣查看关于rails的multi-tenancy

-

多租户

虽然多租户通常是拥有多个数据库/资产(每个用户一个)的定义,但是,因为在rails中工作这是非常困难的(我们目前正在处理的事情) ,你可以使用单一数据堆栈的原理

有几个关于如何使用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 %>
相关问题