Adding a subdomain for different types of users

I am new to Rails and most of my knowledge depends on tutorials :)

So, I followed this http://www.railstutorial.org tutorial and created a really nice site, but now I have a problem. For my users, I have a special column in my database that shows what type of user it is. For example, I have a column “student” that is “true” if the user is a student and “false” if he is not.

Now I would like to create a subdomain for students. So, when a student wants to register or subscribe, he will be transferred to www.student.mysite.com, and not to www.mysite.com.

How can i do this?

Thank:)

+4
source share
1 answer

There are several ways to do this, especially it will be interesting for you multi-tenancyto look regarding rails.

-

Apartment house

While multiple leases are usually a determination of the presence of several databases / assets (one for each user), since it is ridiculously difficult to get this to work on rails (which we are working on now), you can use the principle with one data stack

There are several guides on how to achieve this with Rails here:

, " " " "

-

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 %>
+2

All Articles