How to Use Controller in Ruby on Rails

Contents
In this article, you will learn how to use controller in Ruby on Rails.
How to use controller
In Ruby on Rails, a controller is responsible for handling user requests, retrieving data from the model, and rendering the appropriate view. Here’s a step-by-step guide on how to use a controller in Ruby on Rails:
Generate a controller
To generate a new controller, run the following command in your terminal:
rails generate controller ControllerName
Replace ControllerName with the name of your controller. This command will create a new controller file in the app/controllers directory, along with several other files and folders.
Define actions
Inside your controller file, you can define actions that correspond to user requests. For example, if you want to handle a request to display a list of items, you might define an action like this:
class ItemsController < ApplicationController
def index
@items = Item.all
end
end
This action retrieves all the items from the model and assigns them to an instance variable @items. This instance variable can be used in the corresponding view to display the list of items.
Define routes
To map user requests to your controller actions, you need to define routes in config/routes.rb file. For example, to map requests for the root URL to the index action of the ItemsController, you would add the following line to your routes.rb file:
root 'items#index'
This will tell Rails to route requests to the root URL to the index action of the ItemsController.
Create views
To display data to the user, you'll need to create views that correspond to each of your controller actions. For example, to display the list of items in the index action, you might create a view file app/views/items/index.html.erb that looks like this:
<h1>Items</h1>
<ul>
<% @items.each do |item| %>
<li><%= item.name %></li>
<% end %>
</ul>
This view file displays a heading "Items" and a list of items retrieved from the @items instance variable.