Migration tips
rails g migration ExecuteSomething
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:
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
environment.rb
:
require File.expand_path('../initializers/mysql2_adapter', __FILE__)
If you encounter migration errors about not being able to migrate further:
#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")