cnandreu
cnandreu

Reputation: 5111

Ruby on Rails 3.2.3 not creating foreign keys after rake db:migrate (MySQL db)

class User < ActiveRecord::Base

has_many :comments

end


class Comment < ActiveRecord::Base

belongs_to :user

end

Then I ran: rake db:migrate. I don't get a "user_id" field/column in my Comment table. I also tried: rake db:drop, rake db:create and rake db:migrate. I'm probably missing a step, any ideas?

Upvotes: 1

Views: 917

Answers (2)

Ismael
Ismael

Reputation: 16730

You have to add those to a migration.

You can define if like this in a new migration

add_column :comments, :user_id, :int

or change your migration and use the helper

create_table :comments do |t|
  ...
  t.references :user
end

Upvotes: 2

Suborx
Suborx

Reputation: 3669

You have to define the migration.

when you create the comments model by

rails generate model comment

rails also generate the migration file in your_appication_root/db/migrate/.

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

the important row for you is

t.references :user

or you can define it directly by

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

Upvotes: 3

Related Questions