0
0
Ruby on Railsframework~5 mins

Why routing maps URLs to actions in Ruby on Rails

Choose your learning style9 modes available
Introduction

Routing connects web addresses (URLs) to specific code that runs in your app. It helps the app know what to do when someone visits a page.

When you want to show a list of items on a webpage.
When you need to display a form for users to fill out.
When you want to handle a button click that sends data to the server.
When you want to organize your app so each URL does a clear job.
When you want to make your app easy to navigate with meaningful URLs.
Syntax
Ruby on Rails
Rails.application.routes.draw do
  get '/path', to: 'controller#action'
end
The 'get' method defines a route for a URL using the GET request.
The 'controller#action' tells Rails which code to run for that URL.
Examples
This route sends visitors of '/home' to the home action in the PagesController.
Ruby on Rails
get '/home', to: 'pages#home'
This route handles form submissions sent to '/submit' using POST, running the create action in FormsController.
Ruby on Rails
post '/submit', to: 'forms#create'
This sets the homepage URL ('/') to run the index action in WelcomeController.
Ruby on Rails
root 'welcome#index'
Sample Program

This example shows a route for '/hello' that runs the say_hello action in GreetingsController. When you visit '/hello', it displays 'Hello, world!'.

Ruby on Rails
Rails.application.routes.draw do
  get '/hello', to: 'greetings#say_hello'
end

class GreetingsController < ApplicationController
  def say_hello
    render plain: 'Hello, world!'
  end
end
OutputSuccess
Important Notes

Routes must be unique so Rails knows exactly which code to run.

Use meaningful URLs to help users and search engines understand your site.

Routes can handle different HTTP methods like GET, POST, PUT, DELETE.

Summary

Routing links URLs to specific controller actions in Rails.

This helps your app respond correctly when users visit different pages.

Defining clear routes makes your app organized and easy to use.