2012-04-28 50 views
1
class User < ActiveRecord::Base 

has_many :comments 

end 


class Comment < ActiveRecord::Base 

belongs_to :user 

end 

然後我運行:rake db:migrate。我的評論表中沒有「user_id」字段/列。我也嘗試過:rake db:drop,rake db:create和rake db:migrate。我可能錯過了一個步驟,有什麼想法?Ruby on Rails 3.2.3在rake db:migrate(MySQL db)後不創建外鍵

回答

3

您必須定義遷移。

當您通過

rails generate model comment 

軌的評論模式也產生your_appication_root/DB /遷移/遷移文件。

class CreateComments < ActiveRecord::Migration 
    def change 
    create_table :comments do |t| 
     t.references :user 
     t.text, :content 
     t.timestamps 
    end 
    end 
end 

爲您的重要行

t.references :user 

,或者你可以直接通過

t.integer :user_id 
#but this do not add the db index 
2

定義它,你必須添加這些到遷移。

可以定義如果像這樣在新的遷移

add_column :comments, :user_id, :int 

或更改遷移和使用助手

create_table :comments do |t| 
    ... 
    t.references :user 
end 
相關問題