Adding a column to a table
Migrations showed how a table is born:
bin/rails generate model, columns insidecreate_table, thenbin/rails db:migrate. This is the next thing that happens to every table: a column it needs that wasn't there on day one.
The problem
Your movies table is made and migrated, and your tests are green. Now a new story says every movie has a director, and there is no column for it.
The migration that created the table has already run, and Rails won't run it again. Editing it changes nothing in the database, and it leaves a file that lies about what happened. So the rule from Migrations still holds: never edit a migration you have run.
The fix is not to start over. It is one more migration, one that changes the table instead of creating it.
The new migration
Ask Rails for an empty migration. The name says what it does; Rails only needs it to be unique.
bin/rails generate migration AddDirectorToMovies
That makes a new file in db/migrate/, with a newer timestamp than the one that created the table, so it runs after it. Open it. Its change method is empty. Put one line in it:
class AddDirectorToMovies < ActiveRecord::Migration[8.1]
def change
add_column :movies, :director, :string
end
end
add_column takes the table, the new column and its type: the same types as before, :string for text and :integer for numbers and ids. Then run it:
bin/rails db:migrate
Open db/schema.rb. The movies table now lists director. You didn't write that line; Rails did, from the migration. The rows you already had are still there, each with an empty director until something fills it in.
What it does to your tests
Nothing, until a rule says the column matters. The moment your definition of done says "a movie can't be saved without a director" and the model gets that rule, the tests you already had start to react. Any test that saved a movie on its way to checking something else is now saving one with no director, and what happens next depends on what that test was checking. Read each failure for what the test was relying on, and ask whether any test is now passing for a reason other than its own rule. That is not the tests breaking; that is the tests doing their job. Each of those movies now has to be given a director, the way the real app would. When you ask your agent for the new tests, expect it to touch the old ones too, and read what it changed.
The other direction
A column that should go away is the same shape, with remove_column:
remove_column :movies, :director, :string
A new migration, never an edit to an old one. The database's history is the list of files in db/migrate/, in order, and db/schema.rb shows the database's state up to the most recently executed (i.e. ran) migration.