0
我完全不熟悉ruby,我想爲MySQL數據庫創建一個數據庫遷移腳本。我瀏覽了一些在線材料,我必須創建一個應用程序才能創建遷移腳本。Ruby MySQL數據庫遷移腳本
我可以寫在一個文件數據庫遷移腳本,並以下任務:
- 創建數據庫
- 創建2-3個桌子
- 種子這些表中的一些數據
任何幫助或引用將很大
在此先感謝
我完全不熟悉ruby,我想爲MySQL數據庫創建一個數據庫遷移腳本。我瀏覽了一些在線材料,我必須創建一個應用程序才能創建遷移腳本。Ruby MySQL數據庫遷移腳本
我可以寫在一個文件數據庫遷移腳本,並以下任務:
任何幫助或引用將很大
在此先感謝
只能使用一個寶石mysql2 - https://stackoverflow.com/a/14435522/3102718
或mysql2與ActiveRecord的。
下面是示例遷移文件的:
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
運行它(寶石mysql2
和activerecord
應安裝)。
感謝它的工作,只爲其他人確保你給mysql套接字的正確路徑。 –
你爲什麼要寫一個腳本來做到這一點?是否允許其他人(或稍後的日期)在未來重新創建數據庫? –
是的,我可以使用腳本來做同樣的事情,並可以進行一些上下修改。 –
看看https://github.com/thuss/standalone-migrations。有了這個寶石,你可以使用Rails遷移而不創建Rails項目。 – slowjack2k