有没有一种聪明的方法可以将SQL导出解析为用Ruby编写的Rails db种子文件?

时间:2012-11-13 17:57:44

标签: ruby-on-rails

是否有任何工具可以使用SQL编写的导出数据库文件并将表转换为Rails 3的种子文件?

1 个答案:

答案 0 :(得分:4)

您有两个主要选项

a)使用Rails中的连接和执行功能

示例:

connection = ActiveRecord::Base.connection
statement  = File.read('db//data/icd_10.sql')
connection.execute(statement)

执行以下SQL语句:

=> INSERT INTO `icd_10_ca_codes` (`ICD_10_CA_Code`, `Block`, `Code_id`, `Code_Description`, `Code_Includes`, `Code_Excludes`, `Code_Notes`, `created_at`, `updated_at`)
=> VALUES ('G35', '' , 'Multiple sclerosis', 'Multiple sclerosis (of):
• NOS
• brain stem
• cord
• disseminated
• generalized', NULL, NULL);

b)使用seed_dump gem从SQL数据库导出到种子文件并生成一个带有数据的模板

示例:

$gem install seed_dump 
$rake db:seed:dump MODEL=Icd10Code APPEND=true
$rake db:seed --trace

在种子文件中生成以下内容:

=> Icd10CaCode.create([
=> { :ICD_10_CA_Code => "G35", :Block => "G35", :Code_id => "", :Code_Description => "Multiple sclerosis", :Code_Includes => "Multiple sclerosis (of):\n• NOS\n• brain stem\n• cord\n• disseminated\n• generalized", :Code_Excludes => nil, :Code_Notes => nil, :created_at => "2013-06-24 20:37:24", :updated_at => "2013-06-24 20:37:28" };
=> ], :without_protection => true )

https://github.com/rroblak/seed_dump