Ruby on Rails

Advanced Migrations

Complex migrations, reversible migrations, data migrations, rollbacks, DB constraints vs validations, safe migrations

20 interview questionsยท
Mid-Level
1

What is the difference between the change and up/down methods in a Rails migration?

Answer

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.

2

How to make a migration reversible when Rails cannot automatically infer the reverse operation?

Answer

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.

3

Which command allows rolling back multiple migrations in a single operation?

Answer

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.

4

Why avoid using ActiveRecord model references in data migrations?

5

What is the best practice for performing a data migration in production on a large table?

+17 interview questions

Master Ruby on Rails for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free