Divide large routes.rb to multiple files in Rails 5

Here's a nice article, simple, concise, straight to the point - not mine.

config/application.rb

module YourProject
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/config/routes)
  end
end

config/routes/admin_routes.rb

module AdminRoutes
  def self.extended(router)
    router.instance_exec do
      namespace :admin do
        resources :articles
        root to: "dashboard#index"
      end
    end
  end
end

config/routes.rb

  Rails.application.routes.draw do
    extend AdminRoutes

    # A lot of routes
  end

Rails 6.1+ built-in way to load routes from multiple files.

From official Rails docs:


Breaking up very large route file into multiple small ones:

If you work in a large application with thousands of routes, a single config/routes.rb file can become cumbersome and hard to read.

Rails offers a way to break a gigantic single routes.rb file into multiple small ones using the draw macro.

# config/routes.rb

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

  draw(:admin) # Will load another route file located in `config/routes/admin.rb`
end

# config/routes/admin.rb

namespace :admin do
  resources :comments
end

Calling draw(:admin) inside the Rails.application.routes.draw block itself will try to load a route file that has the same name as the argument given (admin.rb in this case). The file needs to be located inside the config/routes directory or any sub-directory (i.e. config/routes/admin.rb or config/routes/external/admin.rb).

You can use the normal routing DSL inside the admin.rb routing file, however you shouldn't surround it with the Rails.application.routes.draw block like you did in the main config/routes.rb file.


Link to the corresponding PR.


you can write some codes in config/application.rb

config.paths['config/routes.rb'] = Dir[Rails.root.join('config/routes/*.rb')]