2012-04-28 74 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 
相关问题