2012-04-28 4 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:rake db:migrate。私はおそらく一歩、任意のアイデアを逃している?rake db:migrate(MySQL db)の後にRuby on Rails 3.2.3で外部キーが作成されない

答えて

3

移行を定義する必要があります。

あなたはレールもyour_appication_root/DB /移行/で移行ファイルを生成

rails generate model comment 

でコメントモデルを作成します。

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