让Devise在注册时创建子域

我想让Devise在我的网站上创建子域名。

现在,我有两个型号:

  1. 公司: Company可以直接在网站上注册,登录后可以邀请员工。 当公司注册时,我想要创建一个独特的子域名(例如example.com => techcraz.example.com。)

  2. 员工: Employee只有在收到邀请链接时才能注册。

我想要的是什么:

  • 主域名作为注册页面。
  • CompaniesEmployees单一登录页面。
  • 登录时,他们必须提供域名,然后应将其重定向到该子域的登录页面(例如techcraz.example.com/signin。)
  • 输入不存在的URL时,应将其重定向到注册页面。

我是Rails的新手。 请帮忙!

提前致谢!

每个用户一个子域是Web应用程序开发中相当常见的用例。 以下是您可以这样做的方法:

首先:确保您的Users table具有:name column (我认为Devise默认执行此操作 – 如果不是,您可以运行rails g migration AddNameToUsers name:string将此列添加到您的数据库)。

要将此User.name用作子域,我们需要确保它只包含字母数字字符(带有可选的下划线)。 我们还将名称限制为最多32个字符。 最后,我们不希望用户选择诸如“www”之类的名称,这些名称将导致诸如“ http://www.myapp.com ”之类的URL。 以下是app/models/user.rb的validation:

 validates_format_of :name, with: /^[a-z0-9_]+$/, message: "must be lowercase alphanumerics only" validates_length_of :name, maximum: 32, message: "exceeds maximum of 32 characters" validates_exclusion_of :name, in: ['www', 'mail', 'ftp'], message: "is not available" 

可选:修改db / seeds.rb(以便在初始化数据库时创建测试用户):

 user = User.create! :name => 'myname', :email => 'user@example.com', :password => 'password', :password_confirmation => 'password' 

当任何人输入的URL具有与现有用户app/controllers/profiles_controller.rb匹配的子域时,我们将为用户显示个人资料页面:

 class ProfilesController < ApplicationController def show @user = User.where(:name => request.subdomain).first || not_found end def not_found raise ActionController::RoutingError.new('User Not Found') end end 

以下是view app/views/profiles/show.html.erb的示例文件:

 

Profile

<%= @user.name %>

<%= @user.email %>

最后,我们需要为子域实现路由。 创建一个这样的类:

 class Subdomain def self.matches?(request) case request.subdomain when 'www', '', nil false else true end end end 

确保在应用程序启动config/application.rb时自动加载此类:

 config.autoload_paths += %W(#{config.root}/lib) 

确保您的routes.rb文件包含以下路由:

 devise_for :users resources :users, :only => :show constraints(Subdomain) do match '/' => 'profiles#show' end 

如果您为配置文件控制器使用了rails generate – 请确保删除get "profiles/show"路由。

有关在应用程序中使用URL Helpers的信息, 请参阅此页面 (基本上您需要使用new_user_session_url而不是new_user_session_path并且可以指定如下的子域:

 root_url(:subdomain => @subdomain)