Generate Rails migrations from a schema
I am creating a new Rails application which will work with an e开发者_JS百科xisting schema. I have been given the schema SQL but I want to create Rails migrations to populate the database in development. The schema is not overly complicated, with around 20 tables, however I don't want to waste time and risk typos by manually creating the migrations.
Is there a way to generate Rails migrations given a schema's SQL?
Sure, connect your application to your database, then run
rake db:schema:dump
This will give you a db/schema.rb ready with all of your definitions. Now that you have that db/schema.rb, simply copy the contents within the declaration into a new migration. I've done this before, and it works just great.
I prefer to simply write the initial migration's up method with SQL execute calls:
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
NOTES
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
精彩评论