MVC Design Pattern in Rails

The MVC (Model View Controller) design pattern is a fundamental way to organize applications that handle requests and interact with a database.  At its core, Ruby on Rails is a web based MVC framework.

The Model in MVC represents the data model or what maps to a database table in your application.  It has fields for representing different pieces of data in your application.  In this lesson we'll create a Projects model that has two fields (which map to columns in the database): a name and a description.

The View in MVC represents what the uses sees in your application.  I it is the UI or user interface. In web-based applications this is generally represented in HTML.

The Controller in MVC has the responsibility of handling requests from a browser,  doing some processing that generally includes interacting with the Model layer in some way and then returning a view with data from the model to display to a users.

In a nutshell that is what MVC is.

Now, let's build something.  From the RailsBeginnerApp directory where our application lives run the following command:

rails generate scaffold Project name:string description:text

This runs a scaffold generator that will auto-generate all the MVC code for dealing with a Project.

In your IDE (Rubymine or VS Code), take a look at the code that was generated in the controllers/model/views directory under the top-level app directory.  A lot of code was generated for us so we don't have to type it all out manually!  This is one of the super powerful features of Ruby on Rails.

Next from the same command line run the following two commands.

rake db:create
rake db:migrate

The first command will create the databases for our application which by default will use Sqlite; the second command will generate the projects table with the two columns based on the migration that was generated for us (find this code in the db/migrations directory of our application).  Here is what the migration looks like:

class CreateProjects < ActiveRecord::Migration[7.0]
  def change
    create_table :projects do |t|
      t.string :name
      t.text :description

Next let's run the application by running the rails server command from our terminal:

rails server

Now if you open up your Rails application to http://localhost:3000 you'll see the view for listing our Projects.  Play around with creating a new project, editing it and deleting it to get a feel for what Rails has created for us with very little effort!

In our next video we'll start to learn out to make the UI look better so it doesn't hurt our eyes so much!


© 2022 Nimble Labs, LLC. All rights reserved.