2013-12-10 21 views
0

我有一個由PHP構建的存在Web應用程序。如何使用存在的數據庫?

現在我需要通過Rails重建這個應用程序。

我已經有此以下數據中的數據庫:

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

我使用這個如下命令生成用戶模型:

rails g model User 

而且我手動鍵入列到用戶遷移文件:

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

然後我嘗試使用以下命令讀取數據:

@users = User.first 

但它扔我一個錯誤,它告訴我應該使用耙分貝:遷移生成表。

所以我想我應該導出我的數據並使用rake db:migrate來構建我的數據庫結構,然後導入我的數據。

這幾張桌子有點麻煩。

但是,其實我有太多的表(約54),所以我必須手動寫54次遷移。

那麼,有沒有一種簡單的方法來使用存在的數據庫?

BTW,我使用rails4

回答

0

你可以只轉儲表到schema.rb

rake db:schema:dump 

然後將其轉換爲您最初的遷移(001_initial_migration.rb):

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

    def self.down 
    # drop everything 
    end 
end 

你不需要寫54次遷移,一個大的就足夠了。

還有rmre gem,它試圖爲你寫你的模型。

+0

感謝您的回覆,我使用rails4,遷移文件似乎只包含** change **方法,沒有** up **和** down **方法。和** rmre寶石**只支持Rails3 – user3060257

+1

您也可以將self.up的代碼放入rails 4的change方法中 – Jeet

0

你不需要寫遷移存在的表,只寫模型存在的表,例如:

class User < AR 
self.table_name = "users" # your existed table name in db 
# attr_accessible :attrs 
# Associations,remember indicate :foreign_key 
end 

如果要添加新表,做到像往常一樣

相關問題