Split Rails routes into multiple files
Rails routes file can become lengthy if the application becomes huge. It can be difficult to manage routes especially if we have multiple namespace and route action names are similar across namespaces. Splitting Rails routes helps us manage routes easily in an application.
Rails routes file is available at config/routes.rb
by default.
It generally follows the pattern given below.
As we can see, Rails.application.routes
calls method draw
by passing a block of routes defined in this file.
Rails.application.routes
is an instance of
ActionDispatch::Routing::RouteSet.
Let’s take an example config/routes.rb
file with some routes.
To split this routes.rb
file into multiple files:
1. Create a directory config/routes
.
2. Create new files in the config/routes
directory. In this case, admin_routes.rb
, customer_routes.rb
, third_party_routes.rb
Similarly, define customer_routes.rb
and third_party_routes.rb
files.
Make sure these newly created route files are
auto loaded.
Add config/routes
directory files in autoload paths in config/application.rb
This auto loads modules defined in config/routes
directory and can be used in
config/routes.rb
file. Let’s load these routes in config/routes.rb
file as given below.
Run the rails application to verify that routes splitted in multiple files are loaded correctly and they work as expected.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox