Creating Model Classes

In this demonstration, I will show how to create model classes to store and manage data in the database. We will continue to build upon the QuizMe project from the previous demos.

Since we are building a quizzing application, we will need to store questions in the database. At first, the app will only allow multiple choice questions but in a later demo we will see that it’s pretty easy to add other kinds of questions too (e.g., fill in the blank). For multiple choice questions, we need to store the question, answer, and a couple of incorrect options (distractors). Figure 1 shows the corresponding class diagram.

A UML class diagram depicting the McQuestion model class

Figure 1. The McQuestion model class.

1. Creating the McQuestion Model Class

First, generate the McQuestion model class shown in the above class diagram by running the following command:

rails generate model McQuestion question:string answer:string distractor_1:string distractor_2:string

This command generates several key files:

Next, set up the mc_questions table in the database and regenerate the db/schema.rb file, which holds the Rails app’s representation of the database, by running the following command:

rails db:migrate

Finally, confirm that the database was set up correctly by

We have now created our first model class and corresponding database table; however, we have not yet saved any McQuestion records in the database—that will be coming soon!

Code changeset for this part