Introduction
In a Ruby on Rails application, the controller is responsible for handling incoming requests and generating responses. It's the intermediary between the models and views, and it plays a crucial role in the application's architecture. In this blog post, we'll discuss the basics of working with controllers in a Rails application.

Creating a Controller
To create a new controller in a Rails application, use the rails generate controller command. Here's an example:
rails generate controller Users
This will generate a new controller file called users_controller.rb in the app/controllers directory. It will also generate a corresponding view directory called users in the app/views directory.
Actions and Routes
Controllers are made up of actions, which are methods that handle requests and generate responses. By default, Rails provides seven standard actions for controllers: index, show, new, create, edit, update, and destroy. These actions correspond to common CRUD operations in a web application.
To add a custom action to a controller, simply define a new method in the controller file. For example, if you wanted to add a search action to the UsersController, you could define it like this:
class UsersController < ApplicationController def search # handle search request end end
Once you've defined your actions, you'll need to define routes that map incoming requests to the appropriate actions. You can define routes using the config/routes.rb file. For example, if you wanted to define a route that maps requests to the search action of the UsersController, you could define it like this:
Rails.application.routes.draw do get '/users/search', to: 'users#search' end
This would map requests to /users/search to the search action of the UsersController.
Instance Variables and Views
Controllers are also responsible for setting up instance variables that are used by the views to generate HTML. For example, if you wanted to display a list of users in a view, you would define an instance variable in the index action of the UsersController:
class UsersController < ApplicationController def index @users = User.all end end
Then, in the corresponding view file (app/views/users/index.html.erb), you would use the instance variable to generate HTML:
<ul> <% @users.each do |user| %> <li><%= user.name %></li> <% end %> </ul>
0 Comments