Search code examples
ruby-on-railsrubyactiverecord

Ruby: add_reference in migration throws error: Table has no foreign key for


I have this migration:

class AddNotificationSettingToHistoricals < ActiveRecord::Migration[6.1]
  def change
    unless foreign_key_exists?(:sms_historicals, column: :notification_setting_id)
      add_reference :sms_historicals, :notification_setting, foreign_key: true
    end
    unless foreign_key_exists?(:email_historicals, column: :notification_setting_id)
      add_reference :email_historicals, :notification_setting, foreign_key: true
    end
  end
end

but when I run it, it throws this error:

Table 'email_historicals' has no foreign key for notification_settings

What I don't understand is that I have these in the migration:

unless foreign_key_exists?(:email_historicals, column: :notification_setting_id)

Which does throw false.. so yes there is no foreign key, that's why I'm trying to add it.. Yea I'm not sure why its doing this.. Any ideas?


Solution

  • Based on https://gitlab.com/gitlab-org/gitlab/-/issues/394760 It looks like foreign_key_exists? can throw errors if run in a migration before postgres_foreign_keys has the correct columns. A work around they suggest would be to use column_exists? instead

    class AddNotificationSettingToHistoricals < ActiveRecord::Migration[6.1]
      def change
        unless column_exists?(:sms_historicals, :notification_setting_id)
          add_reference :sms_historicals, :notification_setting, foreign_key: true
        end
        unless column_exists?(:email_historicals, :notification_setting_id)
          add_reference :email_historicals, :notification_setting, foreign_key: true
        end
      end
    end