parm530
4/4/2018 - 3:47 PM

Migration

Migration tips

Migrations

  • to create a new migration: rails g migration ExecuteSomething
  • if you create a model migration, Rails will create the table migration: rails g model User
#inside of the migration file for creating a model, the table is created:
#this is the long way to create and remove a table

def up
  create_table :users do |t|
    # t.type :column_name, options
    t.string :name, options
    t.timestamps
  end
end

#options include:
# :limit => size
# :default => value
# :null => true/false
# :after => "existing_column", places new column after the specified column
# index: true

#for integers/floats
# :scale => number
# :precision => number


def down
  drop_table :users
end
  • UP and DOWN methods are opposite of each other and go in reverse order: what you perform first in #up will be reversed and performed last in #down!

  • Now it's time to run the migration: bundle exec rake db:migrate

  • Error may occur about PRIMARY KEY:

    • create file in config/initializers/mysql2_adapter.rb, place the following code inside:
    require 'active_record/connection_adapters/mysql2_adapter'
    
    class ActiveRecord::ConnectionAdapters::Mysql2Adapter
        NATIVE_DATABASE_TYPES[:primary_key] = "int(11) auto_increment PRIMARY KEY"
    end
    
    • add the following line under the require statements in environment.rb: require File.expand_path('../initializers/mysql2_adapter', __FILE__)
  • If you encounter migration errors about not being able to migrate further:

    • Go in the migration file that is causing the error, comment out the migrations that were successful and then run the migrations again (with the corrections made)
    • If all is successful, uncomment out the previous migrations and then run back to version 0 and then run the full set of migrations again.
#running migrations
rake db:migrate

rake db:migrate VERSION=0                     #create migrations from beginning
rake db:migrate VERSION=2486237263721735247   #create migrations from a certain migration file

rake db:migrate status                        #shows which migrations are currently up or down

rake db:migrate:up VERSION=365267832983778    #run this migration file up method
rake db:migrate:down VERSION=365267832983778  #run this migration file down method
rake db:migrate:redo VERSION=365267832983778  #run this migration file runs down then up method


#Column migrations
add_column(table, column_name, type, options)
remove_column(table, column_name)
rename_column(table, column_name, new_column_name)
change_column(table, column, type, options)

#INDEX MIGRATIONS
add_index(table, column_name, options)
remove_index(table, column_name)

#Execute any SQL for the DB
execute("string of sql")