Clean your Rails routes: grouping
In Ruby on Rails, all the routes of a given application can be found within the
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 the time.
That’s why it’s important to find a way to order and maintain your routes.
Let’s have a look to an example to see how we could achieve this task.
Before to start
I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1
Please feel free to spread the word and share this post! 🙏
Fun Facts about Ruby — Volume 1
Fun Facts about Ruby — Volume 1 is a collection of cards..
Thank you for your time!
The my-blog application
Few month ago, we created our
my-blog application. This application provides a way to create and manipulate blogposts.
Also, it provides an
config/routes.rb looks like as following
Here we can clearly isolate 3 entities:
So let’s see how to extract each of these entities in a separate file.
First, we have to manipulate our
This line will redefine the target of our
The target is now all the Ruby files under the
So when your application receives a request, Rails will search the expected route in the routing table defined under the
Now, let’s have a look to the files in this directory
$> tree config/routes
└── users.rb0 directories, 4 files
Note that each file uses the
Rails.application.routes.draw method in order to append our resources to the existing routing table.
Finally, you can remove the
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.