我正在创建一个新的Rails应用程序,它将与现有模式一起使用。我已经获得了这个模式的SQL,但我想创建Rails迁移来填充开发中的数据库。这个模式并不是过于复杂,大约有20个表,但我不想通过手动创建迁移浪费时间并冒着错别字的风险。
有没有一种方法可以根据模式的SQL生成Rails迁移?
我正在创建一个新的Rails应用程序,它将与现有模式一起使用。我已经获得了这个模式的SQL,但我想创建Rails迁移来填充开发中的数据库。这个模式并不是过于复杂,大约有20个表,但我不想通过手动创建迁移浪费时间并冒着错别字的风险。
有没有一种方法可以根据模式的SQL生成Rails迁移?
当然,将您的应用程序连接到您的数据库,然后运行
rake db:schema:dump
这将为您提供一个包含所有定义的db/schema.rb。现在,您有了那个db/schema.rb,只需将声明中的内容复制到新的迁移中即可。我以前就这么做过,效果非常好。
我更喜欢使用SQL执行调用来编写初始迁移的up方法:
class InitialDbStructure < ActiveRecord::Migration
def up
execute "CREATE TABLE abouts (
id INTEGER UNSIGNED AUTO_INCREMENT,
updated_at TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created_at TIMESTAMP,
title VARCHAR(125),
body MEDIUMTEXT,
CONSTRAINT PK_id PRIMARY KEY (id),
INDEX ORDER_id (id ASC)
) ENGINE=InnoDB;"
end
注意事项
You will find, particularly if you are often rebuilding and repopulating tables (rake db:drop db:create db:schema:load db:fixtures:load), that execute statements run far faster than interpreted Ruby syntax. For example, it takes over 55 seconds for our tables to rebuild from Rails migrations in Ruby syntax, whereas execute statements re-generate and re-populate our tables in 20 seconds. This of course is a substantial issue in projects where initial content is regularly revised, or table specifications are regularly revised.
Perhaps of equal importance, you can retain this rebuild and repopulate speed by maintaining a single original migration in executed SQL syntax and re-executing migrations (of that single file) by first gutting your schema.rb and then running rake db:reset before re-populating your tables. Make sure you set :version => 0, so that you will get a new schema, faithful to your migration:
ActiveRecord::Schema.define(:version => 0) do
end