How to use the existing database?


I have a exist web application build by PHP.

Now i need to rebuild this application by Rails.

I already have this following data in database:

| user_id | user_name         | .....
| 1       | david             | .....
| 2       | jobs              | .....

I use this following command to generate User model:

rails g model User

And i type columns into User migration file manually:

 create_table :users do |t|
      t.string :user_name

Then i try to use following command to read data:

@users = User.first

But it throw me an error, It show me should use rake db:migrate to generate table.

So i think i should export my data and use rake db:migrate to build my database structure, And import my data.

It's a little bother for a few table.

But, Actually i have too many tables (about 54), So i must write the 54 migrations manually.

So, is there a easy way to use exist database?

BTW, i use rails4

You could just dump your tables to schema.rb:

rake db:schema:dump

then convert it to your initial migration (001_initial_migration.rb):

class InitialMigration < ActiveRecord::Migration
  def self.up
    # put whole schema.rb here

  def self.down
    # drop everything

You don't need to write 54 migrations, one big one is enough.

There is also rmre gem, which tries to write your models for you.