Clean your Rails routes: grouping
How to separate & group your routes by logical entities
In Ruby on Rails, all the routes of a given application can be found within the config/routes.rb
file.
You add more and more routes in this file as your project grows.
The problem here is that this file potentially becomes very complicated to manage over time.
That’s why finding a way to order and maintain your routes is important.
Let’s look at an example to see how we could achieve this task.
The my-blog application
A few months ago, we created our my-blog
application. This application provides a way to create and manipulate blog posts.
Also, it provides an admin
dashboard.
So the config/routes.rb
looks like as following
Here we can isolate 3 entities:
- The
users
resource - The
posts
resource - The
admin
namespace
So let’s see how to extract each of these entities in a separate file.
First, we have to manipulate our config/application.rb
file
This line will redefine the target of our config.paths['config/routes.rb']
.
The target is now all the Ruby files under the config/routes/
directory.
So when your application receives a request, Rails will search the expected route in the routing table defined under the config/routes
directory.
Now, let’s have a look at the files in this directory
$> tree config/routes
config/routes
├── base.rb
├── admin.rb
├── posts.rb
└── users.rb0 directories, 4 files
Note that each file uses the Rails.application.routes.draw
method to append our resources to the existing routing table.
Finally, you can remove the config/routes.rb
file.
Conclusion
With this implementation, As things progress, you’ll be able to maintain your routes in a very easy way.
And that will be a good introduction to your app for new developers.
Voilà!
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚