2009-09-20 37 views
3

我正試圖在Ruby on Rails應用程序中修改數據庫遷移。我正在使用MySQL作爲我的數據庫,並希望將外鍵添加到正在創建的表中。我正在使用下面的代碼,並且正在遵循在適當的列上創建空值的規範,但沒有外鍵約束被應用。Ruby on Rails數據庫遷移不在MySQL表中創建外鍵

class CreateBookCheckOuts < ActiveRecord::Migration 
    def self.up 
    create_table :book_check_outs do |t| 
     t.integer :book_id, :null => false, :options => 
     "CONSTRAINT fk_book_check_out_books REFERENCES books(id)" 
     t.integer :person_id, :null => false, :options => 
     "CONSTRAINT fk_book_check_out_people REFERENCES people(id)" 
     t.datetime :OutDate, :null => false 
     t.datetime :ReturnDate, :null => true 

     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :book_check_outs 
    end 
end 

回答

6

您可以使用Foreigner寶石。

然後遷移改成這樣:

class CreateBookCheckOuts < ActiveRecord::Migration 
    def self.up 
    create_table :book_check_outs do |t| 
     t.integer :book_id, :null => false 
     t.integer :person_id, :null => false 
     t.datetime :OutDate, :null => false 
     t.datetime :ReturnDate, :null => true 

     t.timestamps 
    end 
    add_foreign_key(:book_check_outs, :books) 
    add_foreign_key(:book_check_outs, :people) 
    end 

    def self.down 
    remove_foreign_key(:book_check_outs, :books) 
    remove_foreign_key(:book_check_outs, :people) 
    drop_table :book_check_outs 
    end 
end 
相關問題