簡體   English   中英

客戶在Rails應用程序中注冊時如何自動創建子域?

[英]How to create subdomain automatically when customer is registering in Rails Application?

假設當客戶在示例Rails應用程序中注冊時,我們有一個用於subdomain的文本字段。如何自動創建該子域並允許我們客戶的用戶僅從該子域登錄?

由於您在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創建一個“子彈”(您可以將其別名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

這將自動設置用戶的子域,您可以將其與答案頂部的代碼一起使用,以將他們定向到適當的操作等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM