2. Adding and Updating DB Columns

Let's go back to our problem of adding a new priority column. Here are the steps we need to achieve this:

Creating a migration file

You can easily create a new migration file by running the following command (you can replace AddPriorityToIdeas with an appropriate name. It can be anything but it should make sense):

rails generate migration AddPriorityToIdeas

This will create a migration file in the db/migrate folder.

Write what needs to be changed in the database in the migration file

Next, we need to edit this file like this:

class AddPriorityToIdeas < ActiveRecord::Migration[6.0]
  def change
    add_column :ideas, :priority, :integer
  end
end

Here we are saying, let's add a column called priority, which is an integer field to the ideas table.

How to Change or Rename Database Columns

You can also change or rename database columns in migration files.

  • To rename database columns

    • rename_column :table_name, :old_column_name, :new_column_name
    • For example, renaming the description column to contents: rename_column :ideas, :description, :contents
  • To change database columns (for example, changing the field type from integer to string)

    • change_column :table_name, :column_name, :new_column_field_type
    • For example, changing the priority column from integer to string: change_column :ideas, :priority, :string

Run rails db:migrate to update the database

Finally, to make these changes, you can run rails db:migrate. The schema.rb file will be automatically updated.

The key takeaway is to never edit the schema.rb file. Instead, create a migration file, edit the file, and run rails db:migrate.