How to Add a Boolean Column to a Database Table in Rails using a Migration
Walk through how to using the migration generator to add a column with the boolean data type to a database table in a Ruby on Rails application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

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

large

Now, let's open this migration file 20151030002052_add_completed_to_tasks.rb and this is what the file looks like:

large

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.

large

Easy isn't it?