What is migration?
Migration is a collection of settings for DataBase. It describes the changes of DataBase. In 1 Migration we can create a Table, change the Table structure like adding a Column, deleting a Column, deleting a Table, and many other things related to DataBase. Thanks to Migration we can choose the changed version of DataBase.
Note: If anyone already uses Git, people can imagine that instead of managing the version of Source Code , Migration will manage the version of Database . On Git each version will correspond to 1 commit , in Migation each version corresponds to 1 Migation file only.
Why use Migration?
The Migration files will be kept with our Source Code. If you want to run Project Rails on a new computer, you can easily move DataBase to that new computer with Migration. In addition, we can also share DataBase changes to project members. You can choose the version of DataBase as you like.
Create Migration
We can create Migration files using the Rails built-in command. For example:
1 2 | rails generate migration PetInformation |
Always use the Camel Case format for the name of Migration. This command will create a file in db / migrate / 20200614041848_pet_information.rb. The file name starts with the time it was created and used the underscore _
on each capital letter of the name Migration. If you create multiple Migration with the same name, the time component of the Migration file will help us use it all. It makes each Migration unique.
1 2 3 4 | ➜ RubyTraining git:(master) rails generate migration PetInformation invoke active_record create db/migrate/20200614041848_pet_information.rb |
Our Migration file will look like this:
1 2 3 4 5 | class PetInformation < ActiveRecord::Migration[5.2] def change end end |
With Migration, you can do many other things:
- Create Table
- Create relationships with the tables
- Change Table
- Change the Column
- Edit Column
- Add Foreign Key
Methods of Migration
Currently, Migration methods have the following:
- add_column
- add_foreign_key
- add_index
- add_reference
- add_timestamps
- change_column_default
- change_column_null
- create_join_table
- create_table
- disable_extension
- drop_join_table
- drop_table
- enable_extension
- remove_column
- remove_foreign_key
- remove_index
- remove_reference
- remove_timestamps
- rename_column
- rename_index
- rename_table
Frequently used commands
- Create Migration:
1 2 | rails generate migration PetInformation |
- Implement Migration:
1 2 | rails db:migrate |
- Execute a certain version of Migration
1 2 | rails db:migrate:up VERSION=20200614041848 |
- Discard the last version of Migration:
1 2 | rails db:rollback |
- Remove the last 4 versions of Migration:
1 2 | rails db:rollback STEP=4 |
I would like to end the article here. Thank you for taking the time to read this article.