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.
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.
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 (
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.
Suggested read for all the fun stuff we can do with routes.