diff --git a/changelog/fix_error_rails_where_not_no_second_argument.md b/changelog/fix_error_rails_where_not_no_second_argument.md new file mode 100644 index 0000000000..437da24eb6 --- /dev/null +++ b/changelog/fix_error_rails_where_not_no_second_argument.md @@ -0,0 +1 @@ +* [#1330](https://github.com/rubocop/rubocop-rails/pull/1330): Fix an error for `Rails/WhereNot` when using placeholder without second argument. ([@earlopain][]) diff --git a/lib/rubocop/cop/rails/where_not.rb b/lib/rubocop/cop/rails/where_not.rb index 742fc56073..96762f5e47 100644 --- a/lib/rubocop/cop/rails/where_not.rb +++ b/lib/rubocop/cop/rails/where_not.rb @@ -43,10 +43,10 @@ def on_send(node) range = offense_range(node) - column_and_value = extract_column_and_value(template_node, value_node) - return unless column_and_value + column, value = extract_column_and_value(template_node, value_node) + return unless value - good_method = build_good_method(node.loc.dot&.source, *column_and_value) + good_method = build_good_method(node.loc.dot&.source, column, value) message = format(MSG, good_method: good_method) add_offense(range, message: message) do |corrector| @@ -72,9 +72,9 @@ def extract_column_and_value(template_node, value_node) value = case template_node.value when NOT_EQ_ANONYMOUS_RE, NOT_IN_ANONYMOUS_RE - value_node.source + value_node&.source when NOT_EQ_NAMED_RE, NOT_IN_NAMED_RE - return unless value_node.hash_type? + return unless value_node&.hash_type? pair = value_node.pairs.find { |p| p.key.value.to_sym == Regexp.last_match(2).to_sym } pair.value.source diff --git a/spec/rubocop/cop/rails/where_not_spec.rb b/spec/rubocop/cop/rails/where_not_spec.rb index d0dfd4ce2a..84d8aeded0 100644 --- a/spec/rubocop/cop/rails/where_not_spec.rb +++ b/spec/rubocop/cop/rails/where_not_spec.rb @@ -12,6 +12,12 @@ RUBY end + it 'registers no offense when using `!=` and anonymous placeholder without second argument' do + expect_no_offenses(<<~RUBY) + User.where('name != ?') + RUBY + end + it 'registers an offense and corrects when using `!=` and anonymous placeholder with safe navigation' do expect_offense(<<~RUBY) User&.where('name != ?', 'Gabe') @@ -89,6 +95,12 @@ RUBY end + it 'registers no offense when using `NOT IN` and named placeholder without second argument' do + expect_no_offenses(<<~RUBY) + User.where("name NOT IN (:names)") + RUBY + end + it 'registers an offense and corrects when using `!=` and namespaced columns' do expect_offense(<<~RUBY) Course.where('enrollments.student_id != ?', student.id)