Skip to content

Commit b1a8c86

Browse files
authored
Merge pull request #1222 from rubocop/fix-where_not-for-implicit-receiver
Fix Rails/WhereNot when using implicit receiver
2 parents c5707aa + 853b1eb commit b1a8c86

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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][])

lib/rubocop/cop/rails/where_not.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def on_send(node)
4646
column_and_value = extract_column_and_value(template_node, value_node)
4747
return unless column_and_value
4848

49-
good_method = build_good_method(node.loc.dot.source, *column_and_value)
49+
good_method = build_good_method(node.loc.dot&.source, *column_and_value)
5050
message = format(MSG, good_method: good_method)
5151

5252
add_offense(range, message: message) do |corrector|
@@ -88,6 +88,7 @@ def extract_column_and_value(template_node, value_node)
8888
end
8989

9090
def build_good_method(dot, column, value)
91+
dot ||= '.'
9192
if column.include?('.')
9293
table, column = column.split('.')
9394

spec/rubocop/cop/rails/where_not_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,17 @@
111111
RUBY
112112
end
113113

114+
it 'registers an offense and corrects when using implicit receiver' do
115+
expect_offense(<<~RUBY)
116+
where('name != ?', 'Gabe')
117+
^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `where.not(name: 'Gabe')` instead of manually constructing negated SQL in `where`.
118+
RUBY
119+
120+
expect_correction(<<~RUBY)
121+
where.not(name: 'Gabe')
122+
RUBY
123+
end
124+
114125
context 'with array arguments' do
115126
it 'registers an offense and corrects when using `!=` and anonymous placeholder' do
116127
expect_offense(<<~RUBY)

0 commit comments

Comments
 (0)