Skip to content

Commit

Permalink
Merge pull request #1222 from rubocop/fix-where_not-for-implicit-rece…
Browse files Browse the repository at this point in the history
…iver

Fix Rails/WhereNot when using implicit receiver
  • Loading branch information
koic authored Dec 19, 2023
2 parents c5707aa + 853b1eb commit b1a8c86
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 b1a8c86

Please sign in to comment.