has_many association migration in Rails
Set up associations in models:
class User < ActiveRecord::Base
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :user
end
Delete the migration file you've shown.
Add references to tasks
table (assuming you already have tasks
table):
rails g migration add_references_to_tasks user:references
Migrate the database:
rake db:migrate
If you don't have tasks
table yet, create one:
rails g migration create_tasks name due_date:datetime user:references # add any columns here
Migrate the database:
rake db:migrate
From now on your tasks will have user_id
attribute.
Add has_many :tasks
to the User
model and belongs_to :user
to the Task
model. In your migration file, delete all the current body of the change
method and include a add_index :tasks, :user_id
line. After that, run the migration normally.
I know this is an old thread but efforts are only to improve on this. I think what you were going for was to show reference foreign key in the table. In which case:
class addTasksToUser < ActiveRecords::Migration
def change
update_table :users do |t|
t.references :task
end
end
Please make sure your references to the table with the primary key is singular.