Adding Columns to a Database Table in Rails with a Migration
Learn how to create new columns in a Rails database by leveraging the migration generator.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson, we are going to talk about database manipulation and database migrations so you can become familiar with how to add columns to a database in a Rails app.

To start, let's add a column to the database by running a migration generator in the console:

rails g migration add_stage_to_projects stage:integer

Running this command will create a new migration file for us with the code preloaded for adding a new column to the projects table.

large

Now, let's open the 20151030004750_add_stage_to_projects.rb file. This file adds a column to the project table with the command:

def change
  add_column :projects, :stage, :integer
end

This line means we are adding a column called stage to the projects table, and this new column is of the integer data type.

Now, go back to the console and run the migration with the command:

rake db:migrate

large

You can check if the table is updated by going to the schema.rb file.

large

If you see, the stage column is added to the projects table and our model now can work with the stage attribute.