Skip to content

Commit 3002691

Browse files
committed
missing_foreign_keys: consider column type for foreign key candidates
1 parent b0d597f commit 3002691

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

lib/active_record_doctor/detectors/missing_foreign_keys.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def detect
2828
# We need to skip polymorphic associations as they can reference
2929
# multiple tables but a foreign key constraint can reference
3030
# a single predefined table.
31-
next unless named_like_foreign_key?(column)
31+
next unless looks_like_foreign_key?(column)
3232
next if foreign_key?(table, column)
3333
next if polymorphic_foreign_key?(table, column)
3434

@@ -37,8 +37,11 @@ def detect
3737
end
3838
end
3939

40-
def named_like_foreign_key?(column)
41-
column.name.end_with?("_id")
40+
def looks_like_foreign_key?(column)
41+
type = column.type.to_s
42+
43+
column.name.end_with?("_id") &&
44+
(type == "integer" || type.include?("uuid"))
4245
end
4346

4447
def foreign_key?(table, column)

test/active_record_doctor/detectors/missing_foreign_keys_test.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,26 @@ def test_present_foreign_key_is_not_reported
2121
refute_problems
2222
end
2323

24+
def test_non_integer_missing_foreign_key_is_reported
25+
Context.create_table(:users) do |t|
26+
t.string :external_id
27+
end
28+
29+
refute_problems
30+
end
31+
32+
def test_uuid_missing_foreign_key_is_reported
33+
skip("#{current_adapter} doesn't support materialized views") if !postgresql?
34+
35+
Context.create_table(:users) do |t|
36+
t.uuid :company_id
37+
end
38+
39+
assert_problems(<<~OUTPUT)
40+
create a foreign key on users.company_id - looks like an association without a foreign key constraint
41+
OUTPUT
42+
end
43+
2444
def test_config_ignore_models
2545
Context.create_table(:companies)
2646
Context.create_table(:users) do |t|

0 commit comments

Comments
 (0)