Search code examples
ruby-on-railsruby-on-rails-4activerecordruby-on-rails-5ruby-on-rails-6

has_many association migration in Rails


I m working on a Rails project (Rails version 4.2.3). I created a User and Task model but did not include any association between them during creation. Now i want one user to have many tasks and one task belonging to one user.

Through rails g migration AddUserToTask user:belongs_to from this thread i was able to insert the foreign user_id key in the tasks table. But how to i add a the has_many migration? I updated the User model:

class User < ActiveRecord::Base
  has_many :customers
end 

but i m not sure how i have to write the migration. So far i wrote this:

class addTasksToUser < ActiveRecords::Migration
  def change
    update_table :users do |t|
      t.has_many :tasks
    end 
    add_index :users, taks_id
  end
end 

But rake db:migrate is not performing any action. Is this the correct way to setup the has_many relationship?


Solution

  • 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.