Skip to content

Instantly share code, notes, and snippets.

@stevenyap
Last active August 4, 2024 18:45
Show Gist options
  • Save stevenyap/7038932 to your computer and use it in GitHub Desktop.
Save stevenyap/7038932 to your computer and use it in GitHub Desktop.
List of rake commands to manage database

Create database

rake db:create

Create database table

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

Run Migrate

  • 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

Duplicate to test database

  • 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

Drop database

rake db:drop

Chaining commands

  • You can chain commands together for faster typing
rake db:drop db:create db:migration db:test:prepare

Seeding the database

  • 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 migration

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

Other database commands

# View all migration logs
rake db:migrate:status
@ishaboo
Copy link

ishaboo commented Feb 11, 2018

Yup.

@haroldrandom
Copy link

Nice summary

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