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
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
2. Create new files in the
config/routes directory. In this case,
Make sure these newly created route files are
config/routes directory files in autoload paths in
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