我們正在製作一個Ruby On Rails web應用程序,每個客戶都有自己的數據庫。
在我們的網站上填寫表格後,需要創建數據庫。如何在rails上覆制ruby中的mySQL數據庫?
我們有一個模板數據庫,其中包含我們需要複製的所有表和列。我如何以編程方式從軌道上的紅寶石做到這一點?
我們正在製作一個Ruby On Rails web應用程序,每個客戶都有自己的數據庫。
在我們的網站上填寫表格後,需要創建數據庫。如何在rails上覆制ruby中的mySQL數據庫?
我們有一個模板數據庫,其中包含我們需要複製的所有表和列。我如何以編程方式從軌道上的紅寶石做到這一點?
從任何控制器,您可以定義以下方法。
def copy_template_database
template_name = "customerdb1" # Database to copy from
new_name = "temp" #database to create & copy to
#connect to template database to copy. Note that this will override any previous
#connections for all Models that inherit from ActiveRecord::Base
ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => template_name, :host => "olddev",
:username => "root", :password => "password" })
sql_connection = ActiveRecord::Base.connection
sql_connection.execute("CREATE DATABASE #{new_name} CHARACTER SET latin1 COLLATE latin1_general_ci")
tables = sql_connection.select_all("Show Tables")
#the results are an array of hashes, ie:
# [{"table_from_customerdb1" => "customers"},{"table_from_customerdb1" => "employees},...]
table_names = Array.new
tables.each { |hash| hash.each_value { |name| table_names << name }}
table_names.each { |name|
sql_connection.execute("CREATE TABLE #{new_name}.#{name} LIKE #{template_name}.#{name}")
sql_connection.execute("INSERT INTO #{new_name}.#{name} SELECT * FROM #{template_name}.#{name}")
}
#This statement is optional. It connects ActiveRecord to the new database
ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
:username => "root", :password => "password" })
end
請注意,我不確定這是否會保持forkey密鑰完整性。我認爲這取決於如何創建模板數據庫。
您可以將您的模板架構創建代碼放入包含所有必需的表/索引/視圖/過程創建語句的腳本中,將其稱爲「template_schema.sql」或其他任何內容,然後在數據庫上運行腳本你的選擇(來自Ruby,如果這就是你以後的),你就完成了。
最好的方法是將每個數據庫對象放在源代碼管理下的單獨文件中(以便輕鬆跟蹤各個對象的更改),然後將它們合併到單個文件中作爲部署的一部分。
通過使用yaml_db
您需要安裝插件,使用耙子任務,更改連接字符串,使其指向新的數據庫轉儲任何防護欄數據庫(包括MySQL)到data.yml文件,然後finaly data.yml裝入任何新的數據庫(包括mysql)使用另一個rake任務。非常簡單。
這就是一些有用的信息。謝謝。 – Tilendor 2008-10-08 16:58:52