Migration là Ruby class mô tả thay đổi schema DB theo thời gian — có thể chạy lên (up/change) hoặc rollback xuống (down).
ruby
class AddAgeToUsers < ActiveRecord::Migration[7.1]
def change
add_column :users, :age, :integer
end
endTại sao không viết SQL trực tiếp:
- Version control được (mỗi migration là 1 file commit-able).
- Portable: change method tự sinh SQL cho mọi DB (PostgreSQL/MySQL/SQLite).
- Team sync: rails db:migrate áp đúng những migration chưa chạy.
- Rollback an toàn: rails db:rollback undo migration gần nhất.