0
0
Ruby on Railsframework~30 mins

Route parameters in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Route parameters
📖 Scenario: You are building a simple Rails app that shows details about books. Each book has a unique ID. You want to create a route that uses this ID in the URL to show the right book.
🎯 Goal: Build a Rails route that uses a route parameter called :id to capture the book's ID from the URL and pass it to the controller.
📋 What You'll Learn
Create a route with a parameter named :id in config/routes.rb
Define a controller action show in BooksController
Use the route parameter params[:id] inside the show action
Add a view file to display the book ID
💡 Why This Matters
🌍 Real World
Web apps often show details for items like products, users, or posts by using route parameters in the URL.
💼 Career
Understanding route parameters is essential for building dynamic web pages and APIs in Rails development jobs.
Progress0 / 4 steps
1
Create the books data hash
Create a hash called BOOKS in app/controllers/books_controller.rb with these exact entries: 1 => 'The Hobbit', 2 => '1984', 3 => 'Pride and Prejudice'.
Ruby on Rails
Need a hint?

Think of BOOKS as a small dictionary that stores book names by their IDs.

2
Add the route with parameter :id
In config/routes.rb, add a route that maps GET /books/:id to the show action of BooksController.
Ruby on Rails
Need a hint?

Use get '/books/:id', to: 'books#show' to capture the :id from the URL.

3
Define the show action using params[:id]
In BooksController, define a show method that sets @book_name to the value from BOOKS using params[:id].to_i.
Ruby on Rails
Need a hint?

Use params[:id].to_i to convert the route parameter to a number and find the book.

4
Create the show view to display the book name
Create a file app/views/books/show.html.erb with this exact content: <h1>Book: <%= @book_name %></h1>.
Ruby on Rails
Need a hint?

This view shows the book name inside an <h1> heading.