Skip to content

Commit 0833796

Browse files
authored
missing_foreign_keys: support tables with destroy_async (#219)
1 parent a6f6ea6 commit 0833796

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

lib/active_record_doctor/detectors/missing_foreign_keys.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ def detect
3131
next unless looks_like_foreign_key?(column)
3232
next if foreign_key?(table, column)
3333
next if polymorphic_foreign_key?(table, column)
34+
next if model_destroyed_async?(table, column)
3435

3536
problem!(table: table, column: column.name)
3637
end
@@ -49,6 +50,18 @@ def polymorphic_foreign_key?(table, column)
4950
another_column.name == type_column_name
5051
end
5152
end
53+
54+
def model_destroyed_async?(table, column)
55+
# Check if there are any models having `has_many ..., dependent: :destroy_async`
56+
# referencing the specified table.
57+
models.any? do |model|
58+
model.reflect_on_all_associations(:has_many).any? do |reflection|
59+
reflection.options[:dependent] == :destroy_async &&
60+
reflection.foreign_key == column.name &&
61+
reflection.klass.table_name == table
62+
end
63+
end
64+
end
5265
end
5366
end
5467
end

test/active_record_doctor/detectors/missing_foreign_keys_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,21 @@ def test_uuid_missing_foreign_key_is_reported
4141
OUTPUT
4242
end
4343

44+
def test_destroy_async_is_not_reported
45+
Context.create_table(:companies).define_model do
46+
# We need an ActiveJob job defined to appease the ActiveRecord
47+
class_attribute :destroy_association_async_job, default: Class.new
48+
49+
has_many :users, dependent: :destroy_async
50+
end
51+
52+
Context.create_table(:users) do |t|
53+
t.references :company, foreign_key: false
54+
end.define_model
55+
56+
refute_problems
57+
end
58+
4459
def test_config_ignore_models
4560
Context.create_table(:companies)
4661
Context.create_table(:users) do |t|

0 commit comments

Comments
 (0)