A migration represents a change we either want to make to a database as a whole, or to the data contained within the database, and it’s expressed in a source file in database-independent terms. These changes can update both the database schema and the data in the database tables. We apply these migrations to update our database, and we can unapply them to roll our database back.

Generate Migration

I am assuming you have a Rails app setup. And if not:

rails new store # :)
cd store

A migration can be generated in Rails with help of a command.

bin/rails generate migration create_products title:string description:text image_url:string price:decimal

This is going to generate a migration file logging out something like this in your bash:

invoke active_record
create    db/migrate/20180314132617_create_products.rb
create    app/models/product.rb

The migration has a UTC-based timestamp prefix ( 20180314132617 ), a name ( create_products ), and a file extension ( .rb , because it’s Ruby code).

The timestamp will be different for you as well, times change.

Applying the Migration

Now that we have out instructions ready to tell it Rails to run it. It’s time we do that, tell Rails to please run the migration.

But before that, we want to make some edits in the migration instructions. Let’s say we want the price of our products to have eight digits of significance and two digits after the decimal.

class CreateProducts < ActiveRecord::Migration[5.1]
  def change
    create_table :products do |t|
      t.string :title
      t.text :description
      t.string :image_url
      t.decimal :price, precision: 8, scale: 2 # <<


Now that we have what we want, we are now ready to apply this migration to our development database. We can do this with help of Rails command bin/rails db:migrate:

~/workspace/store$ bin/rails db:migrate
== 20180314132617 CreateProducts: migrating ===================================
-- create_table(:products)
   -> 0.0013s
== 20180314132617 CreateProducts: migrated (0.0018s) ==========================

And that’s it Rake (which is also just another program), looks for all the unimplemented migrations in the /db/migrate/ directory and applies them.

We must now have a table named products in our development database.