如何在客户在 Rails 应用程序中注册时自动创建子域?
How to create subdomain automatically when customer is registering in Rails Application?
假设当客户在我们的示例 rails 应用程序中注册时,我们有一个 subdomain.how 的文本字段来自动创建该子域并允许我们客户的用户仅从该子域登录?
由于您使用的是 subdomain
的简单文本字段,您只需更改 Devise:
#config/routes.rb
scope constraints: SubDomain do
devise_for :users
end
#lib/sub_domain.rb
module SubDomain
def initializer(router)
@router = router
end
def self.matches?(request)
User.exists? subdomain: request.subdomain
end
end
#app/models/user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, request_keys: [:subdomain]
def self.find_for_authentication(warden_conditions)
where(:email => warden_conditions[:email], :subdomain => warden_conditions[:subdomain]).first
end
end
因为 session_store
将限定为单个 tld(顶级域),您只需更改以上内容。
奖金
更好的方法是自动设置子域,从他们的 username
或其他东西。
您最好使用 friendly_id
to create a "slug" (which you can alias 作为 subdomain
):
#Gemfile
gem 'friendly_id', '~> 5.1'
# You'll have to follow friendly_id's install instructions
#app/models/user.rb
class User < ActiveRecord::Base
extend FriendlyID
friendly_id :username, use: [:slugged, :finders]
alias_attribute :subdomain, :slug
end
这将自动设置用户的子域,您可以将其与答案顶部的代码一起使用,以引导他们执行适当的操作等。
假设当客户在我们的示例 rails 应用程序中注册时,我们有一个 subdomain.how 的文本字段来自动创建该子域并允许我们客户的用户仅从该子域登录?
由于您使用的是 subdomain
的简单文本字段,您只需更改 Devise:
#config/routes.rb
scope constraints: SubDomain do
devise_for :users
end
#lib/sub_domain.rb
module SubDomain
def initializer(router)
@router = router
end
def self.matches?(request)
User.exists? subdomain: request.subdomain
end
end
#app/models/user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, request_keys: [:subdomain]
def self.find_for_authentication(warden_conditions)
where(:email => warden_conditions[:email], :subdomain => warden_conditions[:subdomain]).first
end
end
因为 session_store
将限定为单个 tld(顶级域),您只需更改以上内容。
奖金
更好的方法是自动设置子域,从他们的 username
或其他东西。
您最好使用 friendly_id
to create a "slug" (which you can alias 作为 subdomain
):
#Gemfile
gem 'friendly_id', '~> 5.1'
# You'll have to follow friendly_id's install instructions
#app/models/user.rb
class User < ActiveRecord::Base
extend FriendlyID
friendly_id :username, use: [:slugged, :finders]
alias_attribute :subdomain, :slug
end
这将自动设置用户的子域,您可以将其与答案顶部的代码一起使用,以引导他们执行适当的操作等。