The Capabilities of Nested Routes

Rails is supposed to make our navigation towards creating an application easy. Often during creating an application, we have to maneuver ourselves from one part to another. This is where we need Routes.

The browser (user) makes a request to the controller using routes. The request follows the path from browser to the controller, the controller decides which view file to invoke and then view (html) can turn to controller for the rest of the action. Please refer to the image below.

We can create an instance of an event in your tables using interface powered by your rails (rails s) server. Let us consider the following model structure for example.

made with lucidchart.com

In order to create an instance of D, we need :id from B. But on our interface/browser we need a quick route to create/update an instance of B while also creating/updating an instance of D. We will also need to transfer the :id of B to pass it to the controller#new of D.

In this case, nested routes help us create a custom path to go from B to D which will take the :id of B in params.

First we need to edit the routes.rb file in the ‘config’ folder. For nested params, the routes will look similar to the following example of Artists and Songs.

It will generate the following routes.

We can specify the actions that are limited.

The above example will empower you with specific routes you can notice in your browser’s address bar.

The artist_id in the params is accessible for the songs#edit

Deep nesting: What if you had another model which needs to be added to the equation? Consider the example of Artist, Album and Song. One artist has many albums, and each album has many songs. If we were to route all of them together, it would look something like the following.

Rails guide recommends not to go deeper than 1 level.

Shallow nesting: Collection actions (index, new, create) are scoped under the parent resource. With shallow nesting we can simplify our routes. We can also add shallow: to parent resource.

In the following example, Image A and Image B will generate same routes.

Image A
Image B: this is the same as the image above

Suggested read for all the fun stuff we can do with routes.

--

--

viraj.info

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store