Skip to content

Commit

Permalink
Merge pull request #552 from koic/fix_a_false_positive_for_rails_find…
Browse files Browse the repository at this point in the history
…_each

[Fix #551] Fix a false positive for `Rails/FindEach`
  • Loading branch information
koic authored Sep 25, 2021
2 parents 6f560da + 2984dd4 commit 7c5ecd5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_a_false_positive_for_rails_find_each.md
Original file line number Diff line number Diff line change
@@ -0,0 +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][])
11 changes: 11 additions & 0 deletions lib/rubocop/cop/rails/find_each.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,20 @@ def on_send(node)
private

def ignored?(node)
return true if active_model_error_where?(node.receiver)

method_chain = node.each_node(:send).map(&:method_name)

(cop_config['IgnoredMethods'].map(&:to_sym) & method_chain).any?
end

def active_model_error_where?(node)
node.method?(:where) && active_model_error?(node.receiver)
end

def active_model_error?(node)
node.send_type? && node.method?(:errors)
end
end
end
end
Expand Down
7 changes: 7 additions & 0 deletions spec/rubocop/cop/rails/find_each_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@
expect_no_offenses('User.all.find_each { |u| u.x }')
end

# Active Model Errors slice from the new query interface introduced in Rails 6.1.
it 'does not register an offense when using `model.errors.where`' do
expect_no_offenses(<<~RUBY)
model.errors.where(:title).each { |error| do_something(error) }
RUBY
end

it 'auto-corrects each to find_each' do
expect_offense(<<~RUBY)
User.all.each { |u| u.x }
Expand Down

0 comments on commit 7c5ecd5

Please sign in to comment.