How to add and use Subdomains in your rails app

Mbonu Blessing - Sep 11 '20 - - Dev Community

Hello everyone,

This week, I will be showing you how to write subdomains in your routes.rb file.

I was working on an app recently and was thinking of the best way to use the same server to serve different type of users and I discovered how some apps do this.

They use subdomains.

The main domain will be for marketing purposes or for the landing page and other necessary information while subdomains will be created for the different categories of users or products you might want to use.

Let's use google as an example. google.com points you to the search engine.

  • For the mail, you need to use the mail.google.com
  • For docs, slides, sheets or form, you have docs.google.com
  • For drive, you have drive.google.com etc

For this post, we will build a simple route file with 2 subdomain: admin and platform. Admin subdomain will serve admin users while platform subdomain will be used by the apps main users.

To define a subdomain, you use constraints.

# routes.rb

root "home#index"

constraints subdomain: "admin" do
 get "/" => "dashboard#index"
end

constraints subdomain: "platform" do
 get "/" => "platform#index"
end

From the above, we define a root path on the domain and defined two root paths for our different subdomain.

To reference this new path for a redirect or link_to, you just simple need to pass the subdomain to root_url and rails takes it up from there. Using root_path won't work here because it returns a relative path and not an actually path where the subdomain can be included.

# redirects
redirect_to root_url(subdomain: "admin")

redirect_to root_url(subdomain: "platform")

# link_to
link_to 'Dashboard', root_url(subdomain: "admin")

link_to 'Home', root_url(subdomain: "platform")

That's it for this week. Leave questions and comments below.

Until next week.

. . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player