Skip to content

Commit

Permalink
[Fix #1221] Fix bug in Rails/WhereNot
Browse files Browse the repository at this point in the history
Fix `Rails/WhereNot` which raised an exception when calling `.where` on an
implicit receiver (e.g. inside model code).
  • Loading branch information
bquorning committed Dec 19, 2023
1 parent c5707aa commit 853b1eb
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_where_not_with_implicit_receiver.md
@@ -0,0 +1 @@
* [#1221](https://github.com/rubocop/rubocop-rails/issues/1221): Fix an exception in `Rails/WhereNot` when calling `.where` on an implicit receiver (e.g. inside model code). ([@bquorning][])
3 changes: 2 additions & 1 deletion lib/rubocop/cop/rails/where_not.rb
Expand Up @@ -46,7 +46,7 @@ def on_send(node)
column_and_value = extract_column_and_value(template_node, value_node)
return unless column_and_value

good_method = build_good_method(node.loc.dot.source, *column_and_value)
good_method = build_good_method(node.loc.dot&.source, *column_and_value)
message = format(MSG, good_method: good_method)

add_offense(range, message: message) do |corrector|
Expand Down Expand Up @@ -88,6 +88,7 @@ def extract_column_and_value(template_node, value_node)
end

def build_good_method(dot, column, value)
dot ||= '.'
if column.include?('.')
table, column = column.split('.')

Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/where_not_spec.rb
Expand Up @@ -111,6 +111,17 @@
RUBY
end

it 'registers an offense and corrects when using implicit receiver' do
expect_offense(<<~RUBY)
where('name != ?', 'Gabe')
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `where.not(name: 'Gabe')` instead of manually constructing negated SQL in `where`.
RUBY

expect_correction(<<~RUBY)
where.not(name: 'Gabe')
RUBY
end

context 'with array arguments' do
it 'registers an offense and corrects when using `!=` and anonymous placeholder' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit 853b1eb

Please sign in to comment.