From d470952c66deb4ae9b696f7e7bd3da3f5c32c2bb Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 7 Oct 2021 11:02:05 +0900 Subject: [PATCH] Fix an error for `Rails/FindEach` Follow up to https://github.com/rubocop/rubocop-rails/pull/552#issuecomment-936231105. This PR fixes an error for `Rails/FindEach` when using `where` with no receiver. --- changelog/fix_an_error_for_rails_find_each.md | 1 + lib/rubocop/cop/rails/find_each.rb | 2 ++ spec/rubocop/cop/rails/find_each_spec.rb | 13 ++++++++++++- 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_an_error_for_rails_find_each.md diff --git a/changelog/fix_an_error_for_rails_find_each.md b/changelog/fix_an_error_for_rails_find_each.md new file mode 100644 index 0000000000..0af1be8260 --- /dev/null +++ b/changelog/fix_an_error_for_rails_find_each.md @@ -0,0 +1 @@ +* [#573](https://github.com/rubocop/rubocop-rails/pull/573): Fix an error for `Rails/FindEach` when using `where` with no receiver. ([@koic][]) diff --git a/lib/rubocop/cop/rails/find_each.rb b/lib/rubocop/cop/rails/find_each.rb index d7cfb4d241..81ca1b193e 100644 --- a/lib/rubocop/cop/rails/find_each.rb +++ b/lib/rubocop/cop/rails/find_each.rb @@ -55,6 +55,8 @@ def active_model_error_where?(node) end def active_model_error?(node) + return false if node.nil? + node.send_type? && node.method?(:errors) end end diff --git a/spec/rubocop/cop/rails/find_each_spec.rb b/spec/rubocop/cop/rails/find_each_spec.rb index 8ec27e1943..1fb38af7da 100644 --- a/spec/rubocop/cop/rails/find_each_spec.rb +++ b/spec/rubocop/cop/rails/find_each_spec.rb @@ -45,7 +45,18 @@ # 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) } + class Model < ApplicationRecord + model.errors.where(:title).each { |error| do_something(error) } + end + RUBY + end + + it 'registers an offense when using `where` with no receiver' do + expect_offense(<<~RUBY) + class Model < ApplicationRecord + where(record: [record1, record2]).each(&:touch) + ^^^^ Use `find_each` instead of `each`. + end RUBY end