Mastering Controllers in Ruby on Rails 7: Controller, Routes, and Views

Shah Nawas Khan
6 min readAug 17, 2023

--

The following lesson in this blog post is also available for FREE in the VS Code. Download the latest version of Code Zoomer from your VS Code Extension Marketplace.

Code Zoomer is a VS Code extension that can get you started quickly to learn a specific subject in coding with Rails. Here are some benefits of using the extension:

  • You don’t have to create the Ruby on Rails project from scratch.
  • Copy and paste the code snippet provided into the specified source file in the lessons with ease.
  • Run Terminal and Rails Console commands provided in the lessons with a click of the Run button on the lessons page.

You can certainly cover this same lesson quicker using Code Zoomer, otherwise, let’s continue to the lesson below.

Overview

In Ruby on Rails, controllers and views work together to handle user requests and display information. Controllers handle the logic of the application and interact with models to retrieve and manipulate data. Views are responsible for rendering HTML and presenting information to the user. In this lesson, we’ll cover the basics of controllers and views in Ruby on Rails.

Getting started

This lesson has a pre-packaged project to get you started with this lesson. You need to make sure this project is in ready state before proceeding with the lesson. First, let’s check the state of the current database and its migrations using the command below:

rails db:migrate:status

This command should let you know that all pending migration are already `up`. If any of the migrations are in a `down` status, or you get the `Schema migrations table does not exist yet.` message, run the following command:

rails db:migrate

Check the migration again with `rails db:migrate:status` command to confirm your local project’s database is in ready state.

Creating Controllers

To create a new controller in Ruby on Rails, use the `rails generate` command followed by the controller name:

rails generate controller Users

The `rails generate` command above will help you to create several files as shown below:

create app/controllers/users_controller.rb
invoke erb
create app/views/users
invoke test_unit
create test/controllers/users_controller_test.rb
invoke helper
create app/helpers/users_helper.rb
invoke test_unit

All controller classes would be created in the `app/controllers` folder in your application. Open the controller you just created in `app/controllers/users_controller.rb` as shown below.

Controllers in Ruby on Rails are defined as classes that inherit from the `ApplicationController` class. The `UsersController` currently does not do anything, so let’s add the `index` method that is responsible to handle user requests to list down all `users` available in the `User` model. This user list later would be displayed in a view using HTML.

class UsersController < ApplicationController
end

The index method retrieves all users from the database using the `User.all` method and assigns them to an instance variable called `@users`. Instance variables in controllers are automatically made available to views.

class UsersController < ApplicationController
def index
@users = User.all
end
end

Routes

Routes in Ruby on Rails map URLs to controller actions. To create a new route for the `UsersController`, open the `config/routes.rb` file and add the following line:

get '/users', to: 'users#index'

This maps the URL `/users` to the `index` method of the `UsersController`.

Creating Views

Views in Ruby on Rails are stored in the `app/views` directory and are named after the controller method they correspond to. To create a new view for the `index` method in the `UsersController`, create a new file called `index.html.erb` in the `app/views/users` directory and replace its content with the following code:

<h1>Users</h1>
<p>Total Users : <%= @users.count %></p>

The above code is in HTML and ERB. ERB is a templating system that evaluates Ruby code embedded in a document. The tags starting with `<%=` and ending with `%>` is the ERB code in this sample. This ERB tag would run the Ruby code enclosed in it, and inject the output into the HTML. In the above example, it would evaluate `@users.count` and inject the user count value into the `<p>` tag.

Now that we have everything complete, let’s run this application and see the result. Type `bin/rails server` in your terminal to start the Rails application on your machine. This command would start the `Puma` webserver distributed with Rails, as shown in the following output.

=> Booting Puma
=> Rails 7.0.3 application starting in development
=> Run `bin/rails server - help` for more startup options
Puma starting in single mode…
* Puma version: 5.6.4 (ruby 3.1.2-p20) ("Birdie's Version")
* Min threads: 5
* Max threads: 5
* Environment: development
* PID: 32614
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000
Use Ctrl-C to stop

Now let’s see your application in action by opening your browser and navigating to `http://localhost:3000`. You should see the default Rails info page:

In the routes section, we already create a route to `/users` path. Now let’s navigate to this path, by entering `http://localhost:3000/users` on your browser. Now, you should see the page changes to show the view you created in the previous step. If your user table in your data has no users, the text `Total Users : 0` would be displayed on your page.

You may create some new users to see this value change. On a separate terminal, run the `rails console` command and create new users by entering `User.create(name: “Max Payne”, email: “max.payne@codezoomer.com”)`. This command would create user records in your database. Enter `User.count` in the console and you should see now the user table has 1 record. Refresh your browser page and see the text on the page changed to `Total Users : 1`.

Next, we want our `/users` page to display not just the count but to list every user in our database. To do this let’s add some more code in the view file in `index.html.erb`.

<h1>Users</h1>
<p>Total Users : <%= @users.count %></p>
<ul>
<% @users.each do |user| %>
<li><%= user.name %></li>
<% end %>
</ul>

We added the HTML code to display a list of users using the `<ul>` and `<li>` tags. We also added an ERB code to loop into the list of users in the `@users` instance variable assigned in the `index` method of the `UsersController`. See there is a small difference in the ERB code used above to loop the users. Now we are enclosing the loop code `@users.each do |user|` in the ERB tag starting with `<%` and ending with `%>`. We use this ERB tag if we do not wish to inject the result of Ruby code into the HTML. Since we only want to inject the output of `user.name` code into the `<li>` tag for each user, then we enclosed `user.name` code with the ERB tag starting with `<%=`.

Now, let’s go back to your browser and refresh the page. You now should see a list added where it displays your user’s name. Add more users in the database using the `rails console` and refresh the browser page to see the changes reflected.

Conclusion

In this lesson, we covered the basics of controllers and views in Ruby on Rails. We learned how to create controllers, define controller methods, create views, and map URLs to controller actions.

--

--

Shah Nawas Khan
Shah Nawas Khan

Written by Shah Nawas Khan

I am a computer programmer, loves to learn and teach. I created Code Dryer to help developer save time from doing boring stuff. https://www.codedryer.com/

No responses yet