0
0
Ruby on Railsframework~5 mins

Named routes and path helpers in Ruby on Rails

Choose your learning style9 modes available
Introduction

Named routes give easy names to your URLs so you can use them in your code without typing the full path. Path helpers are methods that generate these URLs for you.

When you want to link to a page in your app without hardcoding the URL.
When you want to redirect users to a specific page after an action.
When you want to keep your URLs consistent and easy to update.
When you want to generate URLs dynamically in views or controllers.
When you want to improve code readability by using meaningful names.
Syntax
Ruby on Rails
get '/articles/:id', to: 'articles#show', as: 'article'

# Then in views or controllers:
article_path(id)  # returns the URL path for the article
article_url(id)   # returns the full URL including domain

The as: option defines the name of the route.

Use _path for relative URLs and _url for full URLs.

Examples
A simple named route without parameters.
Ruby on Rails
get '/profile', to: 'users#show', as: 'profile'

# Usage:
profile_path  # => "/profile"
Named route with a dynamic segment :id.
Ruby on Rails
get '/articles/:id', to: 'articles#show', as: 'article'

# Usage:
article_path(5)  # => "/articles/5"
Using resources generates many named routes automatically.
Ruby on Rails
resources :books

# Usage:
books_path       # => "/books"
new_book_path    # => "/books/new"
book_path(3)    # => "/books/3"
Sample Program

This example shows how to define named routes and use their path helpers to generate URLs. The welcome_path returns "/welcome" and product_path(10) returns "/products/10".

Ruby on Rails
# config/routes.rb
Rails.application.routes.draw do
  get '/welcome', to: 'home#welcome', as: 'welcome'
  get '/products/:id', to: 'products#show', as: 'product'
end

# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def welcome
    render plain: "Welcome page"
  end
end

# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def show
    render plain: "Product ID: #{params[:id]}"
  end
end

# Usage in a view or controller:
# welcome_path  # => "/welcome"
# product_path(10)  # => "/products/10"
OutputSuccess
Important Notes

Always use named routes instead of hardcoding URLs to make your app easier to maintain.

Path helpers automatically handle URL encoding and parameters.

You can see all named routes by running rails routes in your terminal.

Summary

Named routes give easy names to URLs for cleaner code.

Path helpers generate URL strings using these names.

Use as: in routes to create named routes and call _path or _url helpers in your app.