Let's go back to our problem of adding a new priority
column. Here are the steps we need to achieve this:
rails db:migrate
to update the databaseYou 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.
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 tocontents
:rename_column :ideas, :description, :contents
To change database columns (for example, changing the field type from
integer
tostring
)
change_column :table_name, :column_name, :new_column_field_type
- For example, changing the
priority
column frominteger
tostring
:change_column :ideas, :priority, :string
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
.