Ruby on Rails Migrations
What is Migration?
Migration is a set of database instruction. They describe database changes. In migration we can create table, change table, add column, remove column, drop table and many more. We can migrate our database to a latest version or migrate back to a previous version.
Why use Migration?
Migration maintain database schema with our project code. Application database descriptions are stored with our project code. If i want to install our project in new computer we can easily migrate our database. Also we can share database changes with another team members. Developers can migrate database to latest state or if need they can migrate back to previous version.
Generate a Migration
We can create migration file by using generate command. For example:
rails generate migration UserInformation
Always use camel case for migration name. This command will create a file inside db/migrate/20180321055149_user_information.rb
. The file name start with timestamp and use underscore on every uppercase of your migration name. If you create multiple migration in same name then the set of timestamp is help us to use both. It make each migration unique.
Now your migration file looks like:
class UserInformation < ActiveRecord::Migration[5.1]
def change
end
end
By writing migration you can do many more things.
- Creating a Table
- Creating a Join Table
- Changing Tables
- Changing Columns
- Columns Modifiers
- Foreign Keys
Using the Change Method
Currently, the change method supports only these migration definitions:
- add_column
- add_foreign_key
- add_index
- add_reference
- add_timestamps
- change_column_default (must supply a :from and :to option)
- change_column_null
- create_join_table
- create_table
- disable_extension
- drop_join_table
- drop_table (must supply a block)
- enable_extension
- remove_column (must supply a type)
- remove_foreign_key (must supply a second table)
- remove_index
- remove_reference
- remove_timestamps
- rename_column
- rename_index
- rename_table
Important Commands
Generate migration
rails generate migration UserInformation
Running migration
rails db:migrate
Running specific migration
rails db:migrate:up VERSION=20180321055149
Rolling Back
rails db:rollback
To rolling back last 4 migration
rails db:rollback STEP=4
Wrapping Up
At the end we can understand how migration works in Ruby on Rails. It’s help us to work on small and big application, develop application with team and many more. You can learn very deep from their official documentation http://edgeguides.rubyonrails.org/active_record_migrations.html.
Happy Coding