How to split Rails routes into multiple files

Juraj Kostolanský June 15, 2021

If you work on a large Ruby on Rails application with a lot of routes in the config/routes.rb file, you can now easily split that into multiple files. Rails 6.1 brought back the feature that allows you to load external route files from the router.

According to the Rails 6.1 changelog:

This feature existed back in 2012 but got reverted with the incentive that Routing Concerns was a better approach. Turned out that this wasn’t fully the case and loading external route files from the router can be helpful for applications with a really large set of routes. Without this feature, application needs to implement routes reloading themselves and it’s not straightforward.

You can split your large routes.rb file by using the draw macro. This code sample should be self-explanatory:

# config/routes.rb

Rails.application.routes.draw do
  get 'foo', to: 'foo#bar'

  # This will load `config/routes/admin.rb`
# config/routes/admin.rb

namespace :admin do
  resources :comments

The file admin.rb can be located inside the config/routes directory or any sub-directory, for example config/routes/admin.rb or config/routes/external/admin.rb.

Also don’t forget that you shouldn’t surround the code inside the admin.rb file with the Rails.application.routes.draw block.

This feature was introduced by the PR 37892.

Let's stay in touch

Do you like what you read? Subscribe to get my content on web development, programming, system administration, side projects and more. No spam, unsubscribe at any time.