0
0
Ruby on Railsframework~5 mins

Why controllers handle requests in Ruby on Rails

Choose your learning style9 modes available
Introduction

Controllers in Rails act like traffic managers. They receive requests from users and decide what to do next, such as showing a page or saving data.

When a user clicks a link or submits a form on a website
When the app needs to decide which page or data to show based on user actions
When you want to organize how your app responds to different user requests
When you need to connect user input with the right part of your app logic
When you want to keep your app code clean by separating request handling from data and views
Syntax
Ruby on Rails
class ControllerNameController < ApplicationController
  def action_name
    # code to handle request
  end
end
Controllers are Ruby classes ending with 'Controller'.
Each method inside a controller is called an action and handles a specific request.
Examples
This controller action shows a list of all products when the user visits the products page.
Ruby on Rails
class ProductsController < ApplicationController
  def index
    @products = Product.all
  end
end
This action finds and shows a specific user based on the ID from the URL.
Ruby on Rails
class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
  end
end
Sample Program

This simple controller has one action 'hello' that sets a message to show on the page.

Ruby on Rails
class GreetingsController < ApplicationController
  def hello
    @message = "Hello, welcome to our site!"
  end
end
OutputSuccess
Important Notes

Controllers keep your app organized by handling user requests separately from data and views.

Each action corresponds to a URL route that users can visit.

Controllers often use parameters from the request to find or save data.

Summary

Controllers handle user requests and decide what the app should do.

They keep your app organized by separating request logic from data and views.

Each action in a controller responds to a specific user request or URL.