has_many, belongs_to relation in active record migration rails 4

Hasan Iqbal picture Hasan Iqbal · Jul 27, 2013 · Viewed 59.9k times · Source

I have a User model and a Task model. I have not mentioned any relation between them while creating them.

I need to establish that User has_many Tasks and a Task belongs_to User through a migration

What would be the migration generation command for establishing that relationship?

Answer

Alter Lagos picture Alter Lagos · Jul 29, 2013

You could call:

rails g model task user:references

which will generates an user_id column in the tasks table and will modify the task.rb model to add a belongs_to :user relatonship. Please note, you must to put manually the has_many :tasks or has_one :task relationship to the user.rb model.

If you already have the model generated, you could create a migration with the following:

rails g migration AddUserToTask user:belongs_to

which will generate:

class AddUserToTask < ActiveRecord::Migration
  def change
    add_reference :tasks, :user, index: true
  end
end

the only difference with this approach is, the belongs_to :user relationship in the task.rb model won't be created automatically, so you must create it for your own.