Loading...
New webinar: "The Remote Job Search: My Microverse Journey" with graduate Paul Rail
Watch Now

It can be frustrating trying to understand the MVC model used in Rails, especially for beginners. In this article, we'll better understand the model through a brief explanation about how it works. We also create our first application through following the tutorial Step By Step Ruby on Rails Tutorial by Eduardo Baike and Kasey Champion.

Introduction

As you can see in this article on CodeAcademy and the tutorial from TutorialsPoint page, MVC is short for Model, View, and Controller. MVC is a way of organizing your code, where the Model can hold raw data and also have logic to update the controller if its data changes. View code is made up of all the functions that directly interact with the user, making your app look nice. Controller code acts as a liaison between the Model and the View, by receiving user input and deciding what to do with.

Building Our First App

Setting up your machine: Make sure that you have installed RoR according to the Odin Project tutorial on INSTALLING RAILS.

Now, let’s start running on your terminal the following commands:

{% code-block language="js" %}
$ rails new firstapp
$ cd firstapp/
{% code-block-end %}

Open the project in an editor such as VSCode then open the project running the server:

{% code-block language="js" %}
$ rails server
{% code-block-end %}

Now we have our first app! Try opening it in your browser (http://localhost:3000)  and you should see that it is working:

Diagrama  Descrição gerada automaticamente

Common Error Messages

Try to access the first page you want to display by showing a list of players using the address ‘/players’ (http://localhost:3000/players). 

There we go! Now we should see our first message error (see below) saying, 'there is no route to this path’.

Interface gráfica do usuário, Texto, Aplicativo  Descrição gerada automaticamente

What does that mean though? It means we have no route for the path '/players'. Also, be sure to pay attention to the message error that says use the method GET to set up the route. 

So, let's set up our routes to connecting URLs to code.

  1. Go to the file routes.rb inside the folder config and add the line:

{% code-block language="js" %}
Rails.application.routes.draw do
    get '/players',  to:  'players#index'
end
{% code-block-end %}

Where: 

  • get is the HTTP Verb;
  • /players is the Path;
  • players#index is controller#action (we will add the index method inside the players_controller.rb file)
  1. Go to your browser and input the address ‘http://localhost:3000/players’, then refresh your browser (you also might have to reload the server). Now the error says that we don't have a player controller. Can you see here that we are missing the C from the MVC? 
Interface gráfica do usuário, Aplicativo  Descrição gerada automaticamente
  1. Next, let's create a players controller file by typing the below command in your terminal:

{% code-block language="js" %}
$ rails generate controller players
{% code-block-end %}

*Use a plural name for controllers files (check the rails documentation about controller naming conventions to understand better).

  1. Now run your server again and refresh your browser. You should see an error saying you don’t have any actions called ‘index’ in the controller.
Uma imagem contendo Forma  Descrição gerada automaticamente
  1. Add an empty method called ‘index’ in your players_controller.rb file following the below:

{% code-block language="js" %}
class PlayerController < ApplicationController
                                       def index
                                       end
                                  end
{% code-block-end %}

  1. Refresh your browser. You will get an error message because we are still missing a template (the V from MVC), so we do not have a view.
Interface gráfica do usuário, Texto, Aplicativo, Email  Descrição gerada automaticamente

As you can see, when you create a controller, you are also creating a folder called ‘views(empty)’.

So, let’s create a new file inside the view/player called: ‘index.html.erb’. Note that erb allows us to use Ruby in an html file.

  1. Now add something in our index.html.erb file as:

{% code-block language="js" %}
<h1>This is my view coming from a players controller index#action</h1>
{% code-block-end %}

  1. Refresh your browser again and we can see something like this: 

Now we have a template but we do not have access to our database. So, even if we change the name of the action it will work because we are not interacting with the Model.

  1. Next, let’s try creating an instance variable in your controller to get all the players from the model ‘Players’. Note that we do not have a model yet, so let’s do it and see what happens. To do this add the below in your method (action) index inside the players_controller.rb file:  

{% code-block language="js" %}
class PlayerController < ApplicationController
                                       def index
@players = Player.all
                                       end
                                  end
{% code-block-end %}

Before we refresh the browser again, remember: @players is the variable that gets all the players from our model, but we don’t have a model yet. So, refresh your browser and you will see the below error

Interface gráfica do usuário, Texto, Aplicativo, Email  Descrição gerada automaticamente

Remember that the model will hold our data.

  1. Next we create a model called ‘player’, setting up our table with two columns (first_name and last_name) running the commands:

{% code-block language="js" %}
$ rails g model player first_name:string last_name:string
$ rails db:migrate
{% code-block-end %}

Now you won't have an error because we have a Model (the M from MVC), but we still cannot interact with the model to display the data from the database, because our database is empty.

Creating Data in Databases

So, let’s create some datas in our database (model: player) adding the players by console:

  1. Go to your console by typing:

{% code-block language="js" %}
$ rails c
{% code-block-end %}

  1. Add players in our database using the command in your console: 

{% code-block language="js" %}
Console > Player.create(first_name:"name", last_name:"last_name")
{% code-block-end %}

  1. Add as many as you prefer and set up the first_name and last_name as you want. You can display in your console all the players you’ve created by typing:

{% code-block language="js" %}
Console > Players.all
{% code-block-end %}

Now we can access the variable @players in our index.html.erb file. We also can write Ruby code, since @players is an array holding all the players we have created so far. We can write this as:

{% code-block language="js" %}
<h1>This is my view coming from a players controller index#action</h1>
<% @players.each do |player| %>
      <table>
<tr><%=player.first_name%></tr>
<tr><%=player.last_name%></tr>
                 </table>
            <% end %>
{% code-block-end %}

Bonus: try adding more players to your database, then refresh the browser.

Conclusion

Now you know the basic steps to understanding the MVC model. During the creation of your apps, you will follow this path many times. If you see any of the error messages mentioned above, you should now know what to do to fix it. 

Sometimes, the error message is shown differently, with more or less detail, but you should be able to determine the reason for the errors after reading this article.

After this quick overview of the MVC model, you can go further and discover all that Rails can offer. As always, remember to check Rails documentation.

Happy coding!


Subscribe to our Newsletter

Get Our Insights in Your Inbox

Career advice, the latest coding trends and languages, and insights on how to land a remote job in tech, straight to your inbox.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.