- Read Tutorial
- Watch Guide Video
Before modifying our Task
model, I want to show you how to use migrations to add columns to the database. Let's assume you've created a table and you want to add a new column to it. For example, the tasks
table has title
, description
and project_id
, but it would be nice to have another column that says if a task is completed or not. To do that, go to the rails console and type:
rails g migration add_completed_to_tasks completed:boolean
In general, Ruby looks at the first word and the last word, which in this case is add
and tasks
respectively. So, it knows that something has to be added to the tasks
table.
What needs to be added is a field called completed
and the data type of this field is boolean which means completed
can only have the values true
or false
. After you run this command Rails will create the file ..._add_completed_to_tasks.rb
Now, let's open this migration file 20151030002052_add_completed_to_tasks.rb
and this is what the file looks like:
If you see, since we used the proper naming convention in the console, Rails knew exactly what to add. It knew that the name of the table was tasks
, the parameter that needs to be added is completed
and the data type of that parameter is boolean
. This saves a ton of time for us.
This code is put inside a method called change
that in turn, is inside a class called AddCompletedtoTasks
inherited from ActiveRecord:Migration
.
Now, go back to your console and run the command rake db:migrate
to make changes to the database. To see if your command was executed, go to the schema file, and this is what you'll see.
Easy isn't it?