Skip to content

Commit 614639c

Browse files
authored
Merge pull request rails#53937 from fatkodima/mysql-fix-remove-foreign-key-restrict
Fix removing foreign keys with `:restrict` action for MySQL
2 parents c22f7f9 + 62e3bf2 commit 614639c

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

activerecord/lib/active_record/connection_adapters/mysql/schema_statements.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,13 @@ def create_table(table_name, options: default_row_format, **)
8585
super
8686
end
8787

88+
def remove_foreign_key(from_table, to_table = nil, **options)
89+
# RESTRICT is by default in MySQL.
90+
options.delete(:on_update) if options[:on_update] == :restrict
91+
options.delete(:on_delete) if options[:on_delete] == :restrict
92+
super
93+
end
94+
8895
def internal_string_options_for_primary_key
8996
super.tap do |options|
9097
if !row_format_dynamic_by_default? && CHARSETS_OF_4BYTES_MAXLEN.include?(charset)

activerecord/test/cases/migration/foreign_key_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,13 @@ def test_remove_foreign_key_by_the_select_one_on_the_same_table
468468
@connection.foreign_keys("astronauts").map { |fk| [fk.from_table, fk.to_table, fk.column] }
469469
end
470470

471+
def test_remove_foreign_key_with_restrict_action
472+
@connection.add_foreign_key :astronauts, :rockets, on_delete: :restrict
473+
assert_equal 1, @connection.foreign_keys("astronauts").size
474+
@connection.remove_foreign_key :astronauts, :rockets, on_delete: :restrict
475+
assert_empty @connection.foreign_keys("astronauts")
476+
end
477+
471478
if ActiveRecord::Base.lease_connection.supports_validate_constraints?
472479
def test_add_invalid_foreign_key
473480
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false

0 commit comments

Comments
 (0)