Nested resource routing
This course covers nested resource routing in Rails, using the admin routes, controllers and Rails source of one app. It explains how nesting resources :lessons inside resources :courses adds :course_id to the URL. It covers shallow: true and which actions it flattens, singular resource routes with no :id and plural controller names, and member blocks for a custom reorder action. It also covers module: and scope module: for controller subdirectories, and why shallow flattens nested plural resources but leaves singular ones nested.
What you'll learn
- ✓How nesting one resource inside another adds the parent id to the URL and params
- ✓Which actions shallow: true keeps nested and which it flattens to a bare :id
- ✓How singular resource routes drop :id and still map to a plural-named controller
- ✓Adding custom actions with member blocks, and how collection blocks differ
- ✓Using module: and scope module: to place controllers in subdirectories
- ✓Why shallow flattens nested plural resources but not singular ones
Nesting a resource: putting a "belongs to" relationship into the URL
Rails routes: basics, earlier in this series, showed resources :courses, param: :slug, only: [ :show ], this app's routing for public course pages. Every resources call in that course is a single, standalone resource; none of its seven lessons puts one resources block inside another. That course…
Read the full lesson free →Curriculum
7 lessonsNesting a resource: putting a "belongs to" relationship into the URL
Nesting resources :lessons inside resources :courses adds :course_id to the URL, which the controller reads from params.
resources :lessons, shallow: true: Rails' reason for the option
Rails' docs explain shallow: true, which keeps index, new and create nested and flattens member actions to :id.
Singular resource: no :id in the path, and a controller named after the plural
Singular resource routes have no :id segment, map to plural-named controllers, and find records through the parent.
member do...end: a custom action on one record
A member block adds the custom reorder action carrying one record's id, while collection blocks add actions without one.
module: and scope module: routing a URL to a controller subdirectory
The module: and scope module: options change only the controller module, leaving URLs and helper names as they were.
Shallow reaches a nested plural resource, not a singular one
Shallow flattens the nested plural images route but leaves singular challenge and quiz routes fully nested under :lesson_id.
Putting it together: one nested URL, traced through every rule
The lesson reorder route is traced from URL to controller, applying the rule from each earlier lesson.