
Advanced Migrations
Complex migrations, reversible migrations, data migrations, rollbacks, DB constraints vs validations, safe migrations
1What is the difference between the change and up/down methods in a Rails migration?
What is the difference between the change and up/down methods in a Rails migration?
回答
The change method is a simplified syntax introduced in Rails 3.1 that allows Rails to automatically infer the reverse operation. It works for most common operations like add_column or create_table. The up and down methods provide explicit control over apply and rollback operations, which is necessary when Rails cannot automatically infer the reverse, such as during data deletions or complex transformations.
2How to make a migration reversible when Rails cannot automatically infer the reverse operation?
How to make a migration reversible when Rails cannot automatically infer the reverse operation?
回答
The reversible block allows explicitly defining up and down operations within a change method. This is particularly useful for operations like remove_column where Rails needs to know the column type and options to recreate it during rollback. The reversible block offers the flexibility of up/down while keeping the modern change syntax.
3Which command allows rolling back multiple migrations in a single operation?
Which command allows rolling back multiple migrations in a single operation?
回答
The rails db:rollback STEP=n command allows rolling back the last n executed migrations. For example, STEP=3 will roll back the last three migrations in reverse order of their execution. Without the STEP option, only the last migration is rolled back. This command is useful for quickly returning to a previous database state during development.
Why avoid using ActiveRecord model references in data migrations?
What is the best practice for performing a data migration in production on a large table?
+17 面接問題