किसी भी नियंत्रक से, आप निम्न विधि को परिभाषित कर सकते हैं।
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
ध्यान दें कि मुझे यह सुनिश्चित करने के लिए पता नहीं है कि यह फोर्जिग कुंजी अखंडता बनाए रखेगा। मुझे लगता है कि यह टेम्पलेट डेटाबेस कैसे बनाया गया है इस पर निर्भर करता है।
कुछ उपयोगी जानकारी है। धन्यवाद। – Tilendor
क्या मेरा उत्तर आपके लिए काम करता है? या कम से कम मदद? – abarax
मैं वास्तव में कोड के अंदर किए जा सकने वाले कार्यों के लिए खोल पर जाने की आवश्यकता से सावधान हूं। मैं एक अनियंत्रित निर्भरता पेश नहीं करना चाहता हूं। लेकिन आपके द्वारा प्रदान किया गया लिंक पूरी तरह से असंबंधित कुछ के लिए बहुत उपयोगी था। – Tilendor