0
0
Ruby on Railsframework~30 mins

Nested routes in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Nested Routes in Rails
📖 Scenario: You are building a simple blog application where each post can have many comments. You want to organize your routes so that comments are nested inside posts. This helps keep URLs clear and shows the relationship between posts and their comments.
🎯 Goal: Create nested routes in a Rails application so that comments are nested inside posts. This will generate URLs like /posts/:post_id/comments for comments related to a specific post.
📋 What You'll Learn
Create a resource route for posts
Create a nested resource route for comments inside posts
Use the Rails resources method for routing
Ensure the nested routes generate URLs with post_id as a parameter
💡 Why This Matters
🌍 Real World
Nested routes help organize URLs in web apps where one resource belongs to another, like comments belonging to posts.
💼 Career
Understanding nested routes is essential for Rails developers to build clear, maintainable URL structures and RESTful APIs.
Progress0 / 4 steps
1
Set up the posts resource route
In the config/routes.rb file, create a resource route for posts using resources :posts.
Ruby on Rails
Need a hint?

Use resources :posts to create all standard routes for posts.

2
Add nested comments resource inside posts
Inside the resources :posts block, nest the comments resource by adding resources :comments indented inside.
Ruby on Rails
Need a hint?

Indent resources :comments inside the resources :posts do ... end block.

3
Verify nested routes generate correct URL helpers
Check that the nested routes generate URL helpers like post_comments_path(post) and post_comment_path(post, comment) by running rails routes in the terminal.
Ruby on Rails
Need a hint?

Use the terminal command rails routes to confirm the nested routes exist.

4
Add a root route for the application
Add a root route that points to posts#index by adding root 'posts#index' at the bottom of the routes.rb file.
Ruby on Rails
Need a hint?

The root route sets the home page URL to show the posts index.