ActiveRecord Migrations
Summary - why they exist, how they work

Background

  • Great resource: Guide on Migrations
  • When you discover you need a new column or table, you can modify the database
  • E.g.break the “name” field into a “first name” and “last name”
  • Data Migration
    • How do I move over all the user records that were already there?
  • Logic Migration
    • What has to change in the server code to accomodate this change?
  • Does this mean that migration is bad?
    • It’s not good nor bad: it’s unavoidable
    • It’s much more painful when you are ‘in production’
  • Use Rake db:create_migratoin

Example

  • Migrations usually include the standard types
  • Notice change indicates that this is a reversible migration
1class CreateProducts < ActiveRecord::Migration[5.0]
2  def change
3    create_table :products do |t|
4      t.string :name
5      t.text :description
6    end
7  end
8end
Datatypes
  • There are quite a number of available statements (note they are actually medthods!!):
    • 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),
    • 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

Rails commands

  • rails generate migration - creates a new migration. Look it up for how to parameters work
  • rails db:migrate - applies the migrations to the existing databases
  • rails db:rollback - rolls the most recent migration back (un-applies)
  • rails db:reset - drop the database and set it up again

Rake/Sinatra/Activerecord commands

  • rake db:create_migration - creates a new migration. Look it up for how to parameters work
  • rake db:migrate - applies the migrations to the existing databases
  • rake db:rollback - rolls the most recent migration back (un-applies)
  • rake db:reset - drop the database and set it up again