tempra
tempra

Reputation: 2331

How to add reference to an existing column?

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

Upvotes: 0

Views: 692

Answers (1)

tempra
tempra

Reputation: 2331

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.

Upvotes: 2

Related Questions