Skip to content

Commit 7c5ecd5

Browse files
authored
Merge pull request #552 from koic/fix_a_false_positive_for_rails_find_each
[Fix #551] Fix a false positive for `Rails/FindEach`
2 parents 6f560da + 2984dd4 commit 7c5ecd5

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#551](https://github.com/rubocop/rubocop-rails/issues/551): Fix a false positive for `Rails/FindEach` when using `model.errors.where` in Rails 6.1. ([@koic][])

lib/rubocop/cop/rails/find_each.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,20 @@ def on_send(node)
4343
private
4444

4545
def ignored?(node)
46+
return true if active_model_error_where?(node.receiver)
47+
4648
method_chain = node.each_node(:send).map(&:method_name)
49+
4750
(cop_config['IgnoredMethods'].map(&:to_sym) & method_chain).any?
4851
end
52+
53+
def active_model_error_where?(node)
54+
node.method?(:where) && active_model_error?(node.receiver)
55+
end
56+
57+
def active_model_error?(node)
58+
node.send_type? && node.method?(:errors)
59+
end
4960
end
5061
end
5162
end

spec/rubocop/cop/rails/find_each_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,13 @@
4242
expect_no_offenses('User.all.find_each { |u| u.x }')
4343
end
4444

45+
# Active Model Errors slice from the new query interface introduced in Rails 6.1.
46+
it 'does not register an offense when using `model.errors.where`' do
47+
expect_no_offenses(<<~RUBY)
48+
model.errors.where(:title).each { |error| do_something(error) }
49+
RUBY
50+
end
51+
4552
it 'auto-corrects each to find_each' do
4653
expect_offense(<<~RUBY)
4754
User.all.each { |u| u.x }

0 commit comments

Comments
 (0)