Tag: routes

How to Run with Rails: Setup subdomains in your routes

These days the use of subdomains are commonplace amongst businesses, they can be used to divide up public and private sections of an application or simply define an API structure. Therefore, when creating routes for a specific subdomain in your application, you need to ensure these routes are only accessible when hitting the predefined subdomain. It goes without saying this can help to improve security and control the user experience for your customers and administrators.

The first thing we need to do is decide which routes are going to belong to which subdomain and break them up respectively in your config/routes.rb configuration file. In the example below we have two collections of routes which will require access from a different subdomain.

Once we have decided which routes belong to which subdomain we can begin adding constraints to our route resources.; these constraints basically act as validations and/or conditions when a user tries to access a route. You can add a number of different constraints to a route such as IP address, HTTP verb, content type, format and more. We want to constrain a batch of routes for our example, so we decide to use a block constraint with an argument containing the constraint conditions.




In the above example I am passing the AdminSubdomain and AccountSubdomain library classes as a parameter in our route constraints. These library classes utilise the request object to validate whether the subdomain property matches the required subdomain value, thereby returning a true or false value. This class can be extended to include additional validations and/or conditions, which makes it a powerful and clean solution when defining block constraints in your routes.

But what If I just want to just assign a constraint to a single route?

This can also be achieved with little effort by just assigning the constraint directly to the route, for example:

If you’d like more information on how routing works in the Ruby on Rails platform, check out their detailed documentation: http://guides.rubyonrails.org/routing.html

16th March 2016