Skip to content

Commit 59fe981

Browse files
authored
Merge pull request rails#46683 from fatkodima/add_foreign_key-if_not_exists
Fix `add_foreign_key` with `if_not_exists` referencing the same table but via different columns
2 parents f002536 + cf3c04f commit 59fe981

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1118,7 +1118,7 @@ def foreign_keys(table_name)
11181118
# +:deferred+ or +:immediate+ to specify the default behavior. Defaults to +false+.
11191119
def add_foreign_key(from_table, to_table, **options)
11201120
return unless use_foreign_keys?
1121-
return if options[:if_not_exists] == true && foreign_key_exists?(from_table, to_table)
1121+
return if options[:if_not_exists] == true && foreign_key_exists?(from_table, to_table, **options.slice(:column))
11221122

11231123
options = foreign_key_options(from_table, to_table, options)
11241124
at = create_alter_table from_table

activerecord/test/cases/migration/foreign_key_test.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ class Astronaut < ActiveRecord::Base
185185
@connection.create_table "astronauts", force: true do |t|
186186
t.string :name
187187
t.references :rocket
188+
t.references :favorite_rocket
188189
end
189190
end
190191

@@ -233,6 +234,16 @@ def test_add_foreign_key_with_column
233234
assert_equal "fk_rails_78146ddd2e", fk.name unless current_adapter?(:SQLite3Adapter)
234235
end
235236

237+
def test_add_foreign_key_with_if_not_exists_to_already_referenced_table
238+
@connection.add_foreign_key :astronauts, :rockets
239+
@connection.add_foreign_key :astronauts, :rockets, column: "favorite_rocket_id", if_not_exists: true
240+
241+
foreign_keys = @connection.foreign_keys("astronauts")
242+
assert_equal 2, foreign_keys.size
243+
assert foreign_keys.all? { |fk| fk.to_table == "rockets" }
244+
assert_equal ["favorite_rocket_id", "rocket_id"], foreign_keys.map(&:column).sort
245+
end
246+
236247
def test_add_foreign_key_with_non_standard_primary_key
237248
@connection.create_table :space_shuttles, id: false, force: true do |t|
238249
t.bigint :pk, primary_key: true

0 commit comments

Comments
 (0)