提交 a893718c 编写于 作者: Y Yves Senn

fix `remove_reference` with `foreign_key: true` on MySQL. #18664.

MySQL rejects to remove an index which is used in a foreign key constraint:

```
ActiveRecord::StatementInvalid: Mysql2::Error: Cannot drop index 'index_copies_on_title_id': needed in a foreign key constraint: ALTER TABLE `copies` DROP `title_id`
```

Removing the constraint before removing the column (and the index) solves this problem.
上级 9bdb083d
* `remove_reference` with `foreign_key: true` removes the foreign key before
removing the column. This fixes a bug where it was not possible to remove
the column on MySQL.
Fixes #18664.
*Yves Senn*
* `find_in_batches` now accepts an `:end_at` parameter that complements the `:start`
parameter to specify where to stop batch processing.
......
......@@ -662,7 +662,13 @@ def add_reference(table_name, *args)
#
# remove_reference(:products, :supplier, polymorphic: true)
#
# ====== Remove the reference with a foreign key
#
# remove_reference(:products, :user, index: true, foreign_key: true)
#
def remove_reference(table_name, ref_name, options = {})
remove_foreign_key table_name, ref_name if options[:foreign_key]
remove_column(table_name, "#{ref_name}_id")
remove_column(table_name, "#{ref_name}_type") if options[:polymorphic]
end
......
......@@ -95,6 +95,16 @@ class ReferencesForeignKeyTest < ActiveRecord::TestCase
end
end
end
test "foreign key column can be removed" do
@connection.create_table :testings do |t|
t.references :testing_parent, index: true, foreign_key: true
end
assert_difference "@connection.foreign_keys('testings').size", -1 do
@connection.remove_reference :testings, :testing_parent, foreign_key: true
end
end
end
end
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册