Waseem Ahmad

Multiple Route Files in Rails 4

UPDATE: This feture was reverted in favor of fa736e69a197…2d9dbf416b14 . There is also a related discussion

Often in our Rails applications, we end up with a very long config/routes.rb. The application that I am currently working on has a routes file with over 470 lines. As the number of lines grow, the routes file becomes difficult to maintain. Searching where a particular route is defined also becomes quite difficult.

With commit 6acebb38 made by Yehuda Katz, we can specify multiple route files under config/routes/ directory in our application.

Lets say originally our config/routes.rb looks like:

# config/routes.rb
Tesapp::Application.routes.draw do

  resource :session

  resources :comments
  resources :posts
  resource  :profile

  namespace :admin do
    resources :comments
    resources :users
    resources :posts
  end

  root :to => "welcome#index"
end

We can move admin related routes into its own route file to config/routes/admin.rb.

# config/routes/admin.rb

namespace :admin do
  resources :comments
  resources :users
  resources :posts
end

And we tell Rails router to pick admin routes from that file using ActionDispatch::Routing::Mapper::Resources#draw in config/routes.rb.

# config/routes.rb

Tesapp::Application.routes.draw do

  resource :session

  resources :comments
  resources :posts
  resource  :profile

  draw :admin

  root :to => "welcome#index"
end

#draw will try to find a file with the same name as the symbol passed to it and simply call the route generator methods present in it. This way we can make our routes file more manageable and concerned only with one aspect of our application.

Routes will be drawn in the order #draw is called. The routes that are drawn earlier will take precedence over the routes drawn later.

blog comments powered by Disqus
Fork me on GitHub