Home > Software design >  How to add reference to an existing column?
How to add reference to an existing column?

Time:09-10

I have the following table that is migrated already in my Database.

class CreateHouses < ActiveRecord::Migration[7.0]
  def change
    create_table :houses do |t|
      t.bigint :owner_id, null: false
    end
  end
end

I want to create a new migration to update the owner_id field and link it to owners table.

I've previously tried a few, but they all failed. I tried the following but did not worked as well.

class AddOwnerIdRefToOwners < ActiveRecord::Migration[7.0]
  def change
    add_reference :owners, :owner_id, null: false, foreign_key: true
  end
end

CodePudding user response:

I was able to solve it through the documentation. For the convenience of the future devs who will encounter this,

My format should be,

add_foreign_key :<table>, :<foreignTable>, column: :<column>, primary_key: :<foreignColumn>

I solved by the following

add_foreign_key :houses, :owners, column: :owner_id, primary_key: :id

I give credits to @SergioTulentsev for helping me out.

  • Related