0
0
Ruby on Railsframework~5 mins

Nested routes in Ruby on Rails

Choose your learning style9 modes available
Introduction

Nested routes help organize related web pages by showing their connection in the URL. They make it clear which pages belong inside others.

When you have a blog with posts and each post has comments.
When you want to show all orders for a specific customer.
When you have categories and each category has many products.
When you want URLs that reflect a parent-child relationship between resources.
Syntax
Ruby on Rails
Rails.application.routes.draw do
  resources :parents do
    resources :children
  end
end
This creates URLs like /parents/:parent_id/children/:id.
It helps keep related data grouped in the URL and controller.
Examples
This sets up routes so comments belong to posts, e.g., /posts/5/comments/2.
Ruby on Rails
resources :posts do
  resources :comments
end
This creates routes to access orders for a specific user, like /users/3/orders.
Ruby on Rails
resources :users do
  resources :orders
end
This nests products inside categories, showing their connection in URLs.
Ruby on Rails
resources :categories do
  resources :products
end
Sample Program

This code sets up nested routes where books belong to authors. URLs will look like /authors/1/books/2.

Ruby on Rails
Rails.application.routes.draw do
  resources :authors do
    resources :books
  end
end
OutputSuccess
Important Notes

Nested routes can get complex if you nest too deeply; keep nesting to 1 or 2 levels.

Use nested routes when the child resource always belongs to a parent resource.

You can access the parent ID in your controller to find related records.

Summary

Nested routes group related resources in URLs to show their connection.

They create clear, organized paths like /parents/:parent_id/children/:id.

Use them to keep your app structure logical and easy to understand.