我想让Devise在我的网站上创建子域名。
现在,我有两个模型:
公司:Company
可以直接在网站上注册,登录后可以邀请其员工。当公司注册时,我想要创建一个独特的子域名(例如example.com => techcraz.example.com。)
员工:Employee
只有在收到邀请链接时才能注册。
我想要的是什么:
Companies
和Employees
的单一登录页面。我是Rails的新手。请帮忙!
提前致谢!
答案 0 :(得分:10)
每个用户一个子域是Web应用程序开发中相当常见的用例。这是你如何做到的:
首先:确保您的Users table
有一个:name column
(我认为默认情况下Devise会这样做 - 如果不是,您可以运行rails g migration AddNameToUsers name:string
将此列添加到您的数据库中。)
要将此User.name
用作子域,我们需要确保它只包含字母数字字符(带有可选的下划线)。我们还将名称限制为最多32个字符。最后,我们不希望用户选择“www”等名称来生成“http://www.myapp.com”等网址。以下是app/models/user.rb
的验证:
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'
当有人输入的子网域与现有用户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
以下是视图app/views/profiles/show.html.erb
的示例文件:
<h1>Profile</h1>
<h3><%= @user.name %></h3>
<h3><%= @user.email %></h3>
最后,我们需要为子域实现路由。创建一个这样的类:
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"
路由。
See this page有关在您的应用中使用网址助手的信息(基本上您需要使用new_user_session_url
代替new_user_session_path
,并且您可以指定如下的子域名:
root_url(:subdomain => @subdomain)