Amin Bhargav Amin Bhargav - 1 month ago 21
Ruby Question

Ruby MySQL Database Migration Script

I'm completely new to ruby, I want to create a database migration script for a MySQL database. I went through online material where I had to create an app inorder to create migration scripts.

Can I write a database migration script in a single file which does following task :


  1. Create database

  2. Create 2-3 tables

  3. Seed some data in those tables



Any help or reference will be great

Thanks in advance

Answer

You can use only one gem mysql2 - http://stackoverflow.com/a/14435522/3102718

or mysql2 with activerecord.

Here is example of migration file:

create_database.rb

require 'mysql2'

client = Mysql2::Client.new(host: 'localhost', username: 'root')
client.query("CREATE DATABASE my_database")

require 'active_record'

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :email
    end

    add_index :users, :email, unique: true
  end
end

class CreatePosts < ActiveRecord::Migration
  def self.up
    create_table :posts do |t|
      t.references :user, index: true
      t.string :title
      t.text :body
    end
  end
end

ActiveRecord::Base.establish_connection(
  adapter: 'mysql2',
  encoding: 'utf8',
  host: 'localhost',
  database: 'my_database',
  username: 'root',
  socket: '/tmp/mysql.sock'
)

CreateUsers.up
CreatePosts.up

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

user = User.create(email: "test@example.com", name: "User")
user.posts.create(title: "My Post", body: "Lorem ipsum")

Run it with $ ruby create_database.rb (gems mysql2 and activerecord should be installed).