Skip to content

Commit

Permalink
Fix an error for Rails/FindEach
Browse files Browse the repository at this point in the history
Follow up to #552 (comment).

This PR fixes an error for `Rails/FindEach` when using `where` with no receiver.
  • Loading branch information
koic committed Oct 7, 2021
1 parent 284f3e1 commit d470952
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_an_error_for_rails_find_each.md
Original file line number Diff line number Diff line change
@@ -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][])
2 changes: 2 additions & 0 deletions lib/rubocop/cop/rails/find_each.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion spec/rubocop/cop/rails/find_each_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit d470952

Please sign in to comment.