Source: unsplash.com

Clean your Rails routes: nesting

How resources can help you to avoid custom routes?

Tech - RubyCademy
Published in
2 min readFeb 21, 2020

--

Feel free to have a look to the Clean your Rails routes: grouping article.

In Ruby on Rails, the routes are strongly correlated to the concept of resources.

But sometimes, you need to create custom nested routes.

So, in this tutorial, we’ll see how to avoid to create these custom routes.

Example

Few month ago, we created a my-blog application. This application allows you creating and manipulating blogposts.

Let’s have a look to the config/routes.rb file

Well, that makes the job.. But it’s not RESTful!

How refactoring this code to ensure that it follows the RESTful guidelines?

The answer is: by using resources!

Here, we simply define a nested resource with only one CRUD action: create.

So, the route will be defined as following: POST /posts/:id/comments and it’ll look for a CommentsController#create action to be implemented.

⚠️ Try not to implement more than one level of nesting ! It could make your code harder to maintain by creating resource dependencies.

Voilà!

RubyCademy is now available on Youtube! ▶️ 🚀 🤩 💎

We publish short videos (maximum 5 minutes) that talk about technical notions, quick wins and tools (..and a couple of geek stuffs 😅).

Feel free to click on the image below to access our Youtube channel

--

--