Skip to content

Commit

Permalink
Made add_foreign_key retriable with safe_by_default and Active Record…
Browse files Browse the repository at this point in the history
… < 7.1
  • Loading branch information
ankane committed Nov 7, 2024
1 parent 1cf8ba0 commit a1a62e4
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 8 deletions.
4 changes: 2 additions & 2 deletions lib/strong_migrations/safe_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ def safe_add_reference(table, reference, *args, **options)
def safe_add_foreign_key(from_table, to_table, *args, **options)
@migration.reversible do |dir|
dir.up do
# validate option is ignored for Active Record < 7.1
# validate option is unintentionally ignored for Active Record < 7.1
# https://github.com/rails/rails/pull/45896
if ar_version < 7.1 || !connection.foreign_key_exists?(from_table, to_table, **options.merge(validate: false))
if !connection.foreign_key_exists?(from_table, to_table, **options.merge(validate: false))
@migration.add_foreign_key(from_table, to_table, *args, **options.merge(validate: false))
end
disable_transaction
Expand Down
10 changes: 4 additions & 6 deletions test/safe_by_default_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -146,16 +146,14 @@ def test_add_foreign_key_invalid

user.update!(order_id: nil)

migrate AddForeignKey

if ActiveRecord::VERSION::STRING.to_f >= 7.1
migrate AddForeignKey
else
# fail if trying to add the same foreign key in a future migration
assert_raises(ActiveRecord::StatementInvalid) do
migrate AddForeignKey
end
end

# fail if trying to add the same foreign key in a future migration
assert_raises(ActiveRecord::StatementInvalid) do
else
migrate AddForeignKey
end

Expand Down

0 comments on commit a1a62e4

Please sign in to comment.