Skip to content

Instantly share code, notes, and snippets.

@lisaolson
Last active September 30, 2016 19:17
Show Gist options
  • Save lisaolson/469fb990858035fff447bb407af33f54 to your computer and use it in GitHub Desktop.
Save lisaolson/469fb990858035fff447bb407af33f54 to your computer and use it in GitHub Desktop.
Update database schema with migration

Schema Migration

What is Migration?

Migration is a way to alter your databases. It is a subclass of Active Record (the model for representing data and logic. Active Record has a series of methods that can be used to perform tasks on your databse.

Examples:

  • change_column
  • change_table
  • create_table
  • drop_table
  • remove_column
  • remove_index
  • remove_column
  • To make a Migration:

      rails generate model Product name:string description:text

    This would create a migration that looks like this:

        class CreateProducts < ActiveRecord::Migration
          def change
            create_table :products do |t|
              t.string :name
              t.text :description
              
              t.timestamps
              end
          end
        end

    Relational Databases

    To understand schema migration, first it's important to understand what a relational database is. A relational database is a database that contains a table structure rather than individual documents. Mongo is non-relational, Active Record is relational. So with non-relational databases, you would have to create another table and connect the two, rather than with SQL, relational databases, they're connected and updated within one table.

    How does Schema Migration work:

    Schema Migration is used to update a relational databse, either to a newer or older version. Updating the database is done through Schema Migration. This is done using a tool. In Rails, this tool is rake db:migrate. Rails magic!

    What is rake?

    Rake is a Ruby Make to build up a list of tasks.

      $rake --tasks

    ^^ Shows us the list of tasks available. Rake allows us to run tasks, particularly tasks that build off of eachother.

    Why

    Schema migration allows us to have more adaptive databases that don't need to be designed form the ground up every time. It makes the updating process much easier.

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment