Skip to content

Commit 88c85d0

Browse files
authored
missing_presence_validation: ignore counter cache columns (#180)
1 parent a1e60f9 commit 88c85d0

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lib/active_record_doctor/detectors/missing_presence_validation.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def detect
3030
each_attribute(model, except: config(:ignore_attributes)) do |column|
3131
next unless validator_needed?(model, column)
3232
next if validator_present?(model, column)
33+
next if counter_cache_column?(model, column)
3334

3435
problem!(column: column.name, model: model.name)
3536
end
@@ -94,6 +95,12 @@ def presence_validator_present?(model, column)
9495
def inclusion_validator_items(validator)
9596
validator.options[:in] || validator.options[:within] || []
9697
end
98+
99+
def counter_cache_column?(model, column)
100+
model.reflect_on_all_associations(:has_many).any? do |reflection|
101+
reflection.has_cached_counter? && reflection.counter_cache_column == column.name
102+
end
103+
end
97104
end
98105
end
99106
end

test/active_record_doctor/detectors/missing_presence_validation_test.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,38 @@ def test_timestamps_are_not_reported
139139
refute_problems
140140
end
141141

142+
def test_counter_caches_are_not_reported
143+
Context.create_table(:companies) do |t|
144+
t.integer :users_count, default: 0, null: false
145+
end.define_model do
146+
has_many :users
147+
end
148+
149+
Context.create_table(:users) do |t|
150+
t.integer :company_id
151+
end.define_model do
152+
belongs_to :company, counter_cache: true
153+
end
154+
155+
refute_problems
156+
end
157+
158+
def test_counter_caches_with_custom_names_are_not_reported
159+
Context.create_table(:companies) do |t|
160+
t.integer :custom_users_count, default: 0, null: false
161+
end.define_model do
162+
has_many :users, counter_cache: :custom_users_count
163+
end
164+
165+
Context.create_table(:users) do |t|
166+
t.integer :company_id
167+
end.define_model do
168+
belongs_to :company, counter_cache: :custom_users_count
169+
end
170+
171+
refute_problems
172+
end
173+
142174
def test_models_with_non_existent_tables_are_skipped
143175
Context.define_model(:User)
144176

0 commit comments

Comments
 (0)