From the course: Hands-On Introduction: Ruby on Rails

Creating the model

- [Instructor] Let's start the project by creating the most important part, the model. The model is a Ruby class that defines how the information should be stored. It's a representation of the table in the database, and it's where the business logic of the application is defined. To create a model, we'll use a generator. Open the terminal and type rails generate. In this case, we'll use the model generator, and then type the name of the model and a list of the fields the table will have. We'll start with a description. Now, you have to specify the field type. There are several, such as string, integer, Boolean, date. In this case, it'll be text. The model is located inside the models folder as shown in the generator output. If you open it, you can see it's an empty class. Where is the description field? In active_record, the fields aren't defined in the model. They go to the migration. If you open it, you'll see the instructions Rails gives to the database to create the table and the field. This migration can be undone with a rollback. On the migration from the terminal, call in db:migrate. The table is now created. From now on, you can check the database's structure by opening the schema rb file in the db folder. As you can see, in addition to the description field, Rails has created the created_at and updated_at fields, which are automatically updated to keep track of these states. You may wonder where the database is. You can check this in the database YML file in the config folder. This file defines the development, staging, and production environments. You can see that the path where the database is located is specified in each of them, and by the extension, you can see that it's SQLite. At the beginning of the file, a default section indicates the option all the environments share. The adapter option shows that SQLite is indeed used. If you unfold storage, you can see that the database file is there.

Contents