# Ruby on Rails: Simplify Routing with Nested Resources
Nested resources in Rails routing can help you create clean, organized, and maintainable routes by reflecting the relationships between your models.
Consider an example with a Post model and a Comment model, where a Post
has many Comments. Instead of defining separate routes for posts and comments:
# config/routes.rb
Rails.application.routes.draw do
resources :posts
resources :comments
end
You can use nested resources to create hierarchical URLs. Now, the URLs will reflect the relationship between posts and comments.
# config/routes.rb
Rails.application.routes.draw do
resources :posts do
resources :comments
end
end
Nested resources improve your application’s structure and maintainability by creating clean and organized routes.
/posts/:post_id/comments
/posts/:post_id/comments/:id