Nested Resources In Rails.

Sekou Dosso
3 min readMar 8, 2021

I came across with a challenge to build nested route in rails, and I believe that this post can help other junior like myself. The challenge was about to set up a nested route for 3 controllers where: Dog is child of Owner and Meal is a child of Dog. Also, with 2 grouped routes admin and reports.

Objectives:

- Understand the value of nested routes

- Create nested routes

  • Understand how nested resource URL helper are named.

Regular URL

In a regular URL we might imagine the following possible URLs .

get ‘admin/owners’, to: ‘owners#index’

get ‘admin/owners/:id/dogs’, to: ‘dogs#index’

get ‘admin/owners/:id/dogs/:id’, to: ‘dogs#show’

get ‘admin/owners/:id/dogs/:id/meals’, to: ‘meals#show’

get ‘admin/owners/:id/dogs/:id/meals/:id’, to: ‘meals#show’

as we see now we are getting into messy territory. But base of the separation of concern in order to retrieve a specif. meal we really don’t need owner, we only need dog.

Fortunately Just like any other resourced route, Rails provides named helpers for our nested routes as well. And, just like most other things Rails provides, there’s a predictable way to figure out what they are.

We can nest resources more than one level deep in rails like this:

Recap: we have 2 namespaces (admin and reports) for which we need to set up they different routes where dog is child of owner and meal is a child of dog. With the previous nested resources, we are getting a very long and ugly URL.

Recap: we have 2 namespaces (admin and reports) for which we need to set up they different routes.

We will have to work on 3 steps. Route, Controllers and views

In config/route we can nest resources as the following:

To make things less confusing, Rails has a shallow option you can add to nested routes. So with the shallow option, you would do

Controllers

In the controller we will have to create our 2 namespaces folders

Controller/admin

Controller/reports

When you create a new folder under /controllers, Rails will automatically pick that up as a module and expect you to namespace the controller accordingly. We need to modify our admin/owners.rb to look like this:

Controllers/Admin/dogs

Controllers/Reports/dogs

Views

The views folder for a controller module (in this case /admin) expects a subfolder structure that matches the names of the controllers (in this case views/admin/owners).

Views/admin/owners/new.html.erb

Views/reports/dogs/new.html.erb

Summary

Nesting resources is a powerful tool that helps you keep your routes neat and tidy and is better than dynamic route segments for representing parent/child relationships in your system.

However, as a general rule, you should only nest resources one level deep and ensure that you are considering Separation of Concerns in your routing.

--

--