我们正在制作一个Ruby On Rails webapp,每个客户都可以获得自己的数据库.
在我们的网站上填写表格后,需要创建数据库.
我们有一个模板数据库,其中包含我们需要复制的所有表和列.我怎么能以编程方式从ruby on rails上做到这一点?
我不确定你的意思,但你可以使用ruby的命令行功能来转储模板数据库,创建一个新数据库并使用mysqldump程序重新导入它:
> mysqldump -uroot -proot templateDB > dump.sql > mysql -uroot -proot --execute="CREATE DATABASE newDB" > mysql -uroot -proot newDB < dump.sql
以下是从Ruby调用命令行选项的很好的描述.
从任何控制器,您可以定义以下方法.
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
请注意,我不确定这是否会保持foriegn密钥的完整性.我认为这很大程度上取决于模板数据库的创建方式.