user2954587
user2954587

Reputation: 4861

Change reference to different model rails migration

How can I migrate the Referral table to point to point to the PatientProfile id instead of the User id for an existing database (i.e. would like to migrate all existing rows)?

class User
  belongs_to :profile, polymorphic: true
  has_many :referrals

class PatientProfile
  has_one :user, as: :profile

class Referral
  belongs_to :user

I could accomplish this by simply making a migration and renaming the user_id column to be patient_profile_id and changing the reference in the model, however that would not migrate over existing records.

Upvotes: 0

Views: 1880

Answers (1)

j-dexx
j-dexx

Reputation: 10416

I wouldn't simply change the column name. I'd do something like this

class AddPatientProfileToReferrals < ActiveRecord::Migration
  def up
    add_column :referrals, :patient_profile_id
    add_index :referrals, :patient_profile_id

    Referral.reset_column_information

    Referral.includes(:user).find_each do |referral|
      referral.update_attribute(:patient_profile_id, referral.user.profile_id)
    end

    remove_column :referrals, :user_id
  end
end

You probably want to make sure the referrals have a user, and you can simply reverse the process to write the down method.

Upvotes: 1

Related Questions