3

I have a sql script file that upon import creates a table in a MySQL database and fills it with 2800 record. These are all the postal codes for the country Belgium.

Now I would like to make a Ruby on Rails database migration file from this. Any idea how I can do this?

Maybe there is a way around? Telling in a database migration file to execute a separate sql script?

Thanks, Michael

Michael Torfs
  • 828
  • 2
  • 9
  • 24

1 Answers1

11

If your config/database.yml is referencing the MySQL database with the schema, then do

rake db:schema:dump

That will create a db/schema.rb file which is database independent.

Copy schema.rb into db/migrate/001_original_schema.rb:

class OriginalDatabaseMigration < ActiveRecord::Migration
  def self.up
    # schema.rb here
  end

  def self.down
    # drop all the tables
  end
end
duncan
  • 6,113
  • 3
  • 29
  • 24
  • Hi, Thanks! Just tried it, it generates indeed the structure of the table. Is there also a command that will also include a dump of the records in the tables? – Michael Torfs May 02 '10 at 20:34
  • 1
    If you need to add records which are needed so that the database is usable, then don't do it it in the migrations which is for the database schema. Rails now has a special place for initial data. Use db/seeds.rb. You can convert/dump them to fixtures (google) and then use Fixtures.load or YAML.load with the associated ActiveRecord model to create the entries, or if you got them in a text file, just read it iterating while calling Postalnumber.create. You can even use open-uri and get the data from the internet in seed.rb :-) – duncan May 02 '10 at 21:25