如何在生产中删除fk约束

时间:2018-04-11 15:39:35

标签: ruby-on-rails postgresql

我在制作中遇到以下情况:

我的PersonalInfo模型是使用t.references :user, foreign_key: true, index: true, unique: true模拟Users创建的。但是,PersonalInfo变为多态,这种迁移:

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

问题:

仍然是数据库中的fk约束:

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

我如何构建迁移以安全地删除此约束? (我认为多态关联不需要约束,只有索引)

1 个答案:

答案 0 :(得分:1)

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

请参阅: