Ruby on Rails Q & A

 

How to handle subdomains in Rails?

In a Rails application, handling subdomains is often crucial for multi-tenant apps or when distinct sections of an application need to operate under different subdomains. Rails provides a set of tools that make working with subdomains straightforward.

 

  1. Routing Constraints:

   Rails’ routing system allows you to define constraints based on the request’s attributes. The subdomain can be accessed via `request.subdomain`. For instance, you can route requests based on specific subdomains:

 

 ```ruby

   constraints(subdomain: 'admin') do

     # Routes for the 'admin' subdomain

   end

   ```

 

  1. Dynamic Subdomain Routing:

   You can also capture the subdomain as a parameter:

 


   ```ruby

   constraints(lambda { |req| !req.subdomain.blank? && req.subdomain != 'www' }) do

     get ':controller/:action', to: 'subdomains#show'

   end

   ```

 

   Here, any subdomain other than ‘www’ is captured and processed.

 

  1. Subdomain Helpers:

   When setting up multi-tenant applications, you might find the `request.subdomain` method frequently used. It’s helpful to create helper methods in the `ApplicationController` to identify the current tenant or subdomain context:

 

 ```ruby

   def current_subdomain

     request.subdomain

   end

   helper_method :current_subdomain

   ```

 

  1. Scoped Views and Controllers:

   Depending on the subdomain, you might want to display different views or execute different controller actions. This can be achieved using the current subdomain context to render different templates or execute different logic.

 

  1. Setting Up Development Environment:

   Handling subdomains locally can be tricky. One solution is to use a tool like `lvh.me`, which points to `127.0.0.1` (your local machine). By visiting, for example, `admin.lvh.me:3000`, you can simulate the ‘admin’ subdomain on your local machine.

 

Rails provides comprehensive tools and patterns for working with subdomains, making it feasible to structure complex or multi-tenant applications with distinct behaviors for different subdomains. Proper routing, combined with controller and view logic based on subdomains, offers a robust and scalable solution.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Senior Software Engineer with a focus on remote work. Proficient in Ruby on Rails. Expertise spans y6ears in Ruby on Rails development, contributing to B2C financial solutions and data engineering.