Ruby-on-rails – Rails: Remove foreign key constraint

rails-migrationsruby-on-rails

I have following association with user and semester. And I created user table with semester id as foreign key. So user is not created if semester id not present. But semester id is optional in the registration form.

class User < ApplicationRecord
  belongs_to :semester
end
class Semester < ApplicationRecord
  has_many :users
end
    class CreateUsers < ActiveRecord::Migration[5.1]
      def change
        create_table :users do |t|
          t.string :email
          t.references :semester, foreign_key: true
          t.timestamps
        end
      end
    end

So how can I create another migration to drop the foreign key constraint? So in the user table I there should be two columns email and semester_id but semester_id should not have foreign key constraint because it is an optional field.

Best Answer

class RemoveSemestersFKFromUsers < ActiveRecord::Migration[5.1]
  def change
    if foreign_key_exists?(:users, :semesters)
      remove_foreign_key :users, :semesters
    end
  end
end

Remember to set the association as optional: true to remove the presence validation as well.

Related Topic