2016-10-22 159 views
0

我完全不熟悉ruby,我想为MySQL数据库创建一个数据库迁移脚本。我浏览了一些在线材料,我必须创建一个应用程序才能创建迁移脚本。Ruby MySQL数据库迁移脚本

我可以写在一个文件数据库迁移脚本,并以下任务:

  1. 创建数据库
  2. 创建2-3个桌子
  3. 种子这些表中的一些数据

任何帮助或引用将很大

在此先感谢

+0

你为什么要写一个脚本来做到这一点?是否允许其他人(或稍后的日期)在未来重新创建数据库? –

+0

是的,我可以使用脚本来做同样的事情,并可以进行一些上下修改。 –

+0

看看https://github.com/thuss/standalone-migrations。有了这个宝石,你可以使用Rails迁移而不创建Rails项目。 – slowjack2k

回答

0

只能使用一个宝石mysql2 - https://stackoverflow.com/a/14435522/3102718

mysql2ActiveRecord的

下面是示例迁移文件的:

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: "[email protected]", name: "User") 
user.posts.create(title: "My Post", body: "Lorem ipsum") 

$ ruby create_database.rb 运行它(宝石mysql2activerecord应安装)。

+0

感谢它的工作,只为其他人确保你给mysql套接字的正确路径。 –