0

I have the following situation in production:

My PersonalInfo model was created using t.references :user, foreign_key: true, index: true, unique: true to model Users. However, PersonalInfo became polymorfic, with this migration:

class AddInfoOwnerToPersonalInfos < ActiveRecord::Migration[5.1]
  def up
    rename_column :personal_infos, :user_id, :info_owner_id
    add_column :personal_infos, :info_owner_type, :string

    add_index :personal_infos, [ :info_owner_type, :info_owner_id]

    PersonalInfo.update_all(info_owner_type: 'User')

    change_column :personal_infos, :info_owner_type, :string, null: false
  end

  def down
    rename_column :personal_infos, :info_owner_id, :user_id
    remove_column :personal_infos, :info_owner_type
  end
end

The problem:

Still remain a fk constraint in database:

ALTER TABLE ONLY public.personal_infos ADD CONSTRAINT fk_rails_796da13f22 FOREIGN KEY (info_owner_id) REFERENCES public.users(id);

How could I build a migration to remove safely this constraint? (I believe no constraint is needed in polymorphic associations, only the index)

rwehresmann
  • 1,108
  • 2
  • 11
  • 27
  • Possible duplicate of [Rails Migration: Remove constraint](https://stackoverflow.com/questions/5682068/rails-migration-remove-constraint) – MrTheWalrus Apr 11 '18 at 18:18
  • @MrTheWalrus not a duplicate. That question is a about making the column nullable. – max Apr 11 '18 at 18:53

1 Answers1

1
if foreign_key_exists?(:personal_infos, :users) 
  remove_foreign_key(:personal_infos, :users)    
end

See:

max
  • 96,212
  • 14
  • 104
  • 165