Learn Ruby on Rails Book

Models & Migrations

Creating Task Model

In Rails Models are stored in app/models. Rails encourages us to have model names as singular noun.

Let's create a new file using touch command.

1touch app/models/task.rb

Open file app/models/task.rb and add following lines and save the file.

1class Task < ApplicationRecord
2end

We have created our first model.

Adding a migration to create tasks table

Ruby on Rails uses migrations to alter database. Let's generate our first migration.

1bundle exec rails generate migration CreateTasks
1Running via Spring preloader in process 15478
2      invoke  active_record
3      create    db/migrate/20190128151553_create_tasks.rb

We see a file is generated under the db/migrate folder. This is where all the migrations reside.

Now, let's add a table to our Task model. Rails encourages us to have pluralized version of the model name as name of the table. The plural version of Task is Tasks. So Tasks will be the name of the table.

While creating the table we also want to create a column called title.

It is a general convention in Rails that all tables should have created_at and updated_at columns. This is accomplished by adding t.timestamps in the migration as shown below.

Open the file under db/migrate and add following two lines to it.

1class CreateTasks < ActiveRecord::Migration[6.0]
2  def change
3    create_table :tasks do |t|
4      t.text :title
5      t.timestamps
6    end
7  end
8end

Running the migration

Now that we have added the migration file, let's run the migration so that it takes effect and table tasks is created in our database. Run the following command in your terminal.

1bundle exec rails db:migrate
1== 20190128151553 CreateTasks: migrating =====================================
2-- create_table(:tasks)
3   -> 0.0015s
4== 20190128151553 CreateTasks: migrated (0.0015s) ============================
1git add -A
2git commit -m "Added migrations for tasks table"

Open db/schema.rb and you will see create_table statement there.