0
0
Ruby on Railsframework~5 mins

Route parameters in Ruby on Rails

Choose your learning style9 modes available
Introduction

Route parameters let your app get information from the URL. This helps show different content based on what the user asks for.

Showing a user profile page based on the user ID in the URL.
Displaying a blog post using the post's unique ID from the URL.
Filtering products by category name passed in the URL.
Navigating to a specific order detail page using order number in the URL.
Syntax
Ruby on Rails
get '/items/:id', to: 'items#show'

Use a colon (:) before a word to mark it as a route parameter.

The parameter value is accessible in the controller as params[:id].

Examples
This route captures user_id from the URL and sends it to the show action in UsersController.
Ruby on Rails
get '/users/:user_id', to: 'users#show'
This route uses two parameters: post_id and id, useful for nested resources like comments on posts.
Ruby on Rails
get '/posts/:post_id/comments/:id', to: 'comments#show'
This route uses a parameter name to filter products by category name.
Ruby on Rails
get '/categories/:name/products', to: 'products#index'
Sample Program

This example sets a route with a parameter :id. When you visit /books/5, it shows "Showing book with ID: 5".

Ruby on Rails
Rails.application.routes.draw do
  get '/books/:id', to: 'books#show'
end

class BooksController < ApplicationController
  def show
    book_id = params[:id]
    render plain: "Showing book with ID: #{book_id}"
  end
end
OutputSuccess
Important Notes

Route parameters are always strings. Convert them if you need numbers.

Be careful with parameter names to avoid conflicts with other routes.

Summary

Route parameters let you capture parts of the URL to use in your app.

They are defined with a colon before the name in the route path.

You access them in the controller with params[:parameter_name].