rake db:create
This will creates a migration file in /db/migrate without table definition.
rails g migration create_<TABLE>
Add your table definition in the file.
class CreatePorts < ActiveRecord::Migration
def change
create_table :ports do |t|
t.string :name
t.text :description
t.string :city
t.string :country
t.timestamps
end
end
end
- You need to run migration before ROR actually creates it in the database
- You must run this everytime there is a new migration
rake db:migrate
- This should be ran after rake db:migrate
- This duplicates your schema into the test database so that your test cases will work
- Common error in test cases when you forget this step
rake db:test:prepare
rake db:drop
- You can chain commands together for faster typing
rake db:drop db:create db:migration db:test:prepare
- Note that seeding of database should be idempotent (running it multiple times does not create duplicated records)
- Add your ruby commands to add data in /db/seeds.rb like below:
puts "** Seeding Database: seeding ***\n\n"
unless User.where(email: "[email protected]").first
User.create!(email: '[email protected]',
password: '123123',
password_confirmation: '123123')
puts "-- Created [email protected] with password 123123\n"
end
unless Company.where(name: "ABC").first
Company.create!(name: "ABC")
puts "-- Created company: ABC\n"
end
puts "\n** Seeding Database: completed ***"
Run the command below to seed the data according to seeds.rb
rake db:seed
Roll back the last migration
rake db:rollback
Or you can specify how many steps (n) to rollback. (Specify STEP=9999 to rollback everything)
rake db:rollback STEP=n
Or you can specfiy exactly the version of migration to rollback to
rake db:migrate:down VERSION=847583457438957
Or to simply rerun last migration
rake db:migrate:redo
Tip: If you are changing the latest migration, you should rake db:rollback and then add your new code to the migration file and then run rake db:migrate again
# View all migration logs
rake db:migrate:status
Yup.