Rails: add foreign key to existing column with different column names

Reference migration

class CreateBranches < ActiveRecord::Migration[5.1]
  def change
    create_table :branches do |t|
      t.string :name
      t.string :email
      t.string :phone
      t.string :alternate_phone
      t.string :mobile
      t.integer :contact_one_id, index: true #add columns as integer
      t.integer :contact_two_id, index: true #add columns as integer
      t.references :address, foreign_key: true

      t.timestamps
    end
    #add foreign key constraints on columns
    add_foreign_key :branches, :employees, column: :contact_one_id
    add_foreign_key :branches, :employees, column: :contact_two_id
  end
end

and put belongs_to relation in Branch model

class Branch < ApplicationRecord
  belongs_to :contact_one, class_name: 'Employee'
  belongs_to :contact_two, class_name: 'Employee'
end

Advertisements

Author: Santosh Singh

Father, Software Engineer, Traveller

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s