From bd4f92bb8b5d138cf9f12208574728c4721fe26c Mon Sep 17 00:00:00 2001 From: Jamie McCarthy Date: Sun, 24 Sep 2023 15:51:23 +0000 Subject: [PATCH] [Fix #1130] Fix crash for Rails/UniqueValidationWithoutIndex with bare validate --- .../fix_bug_unique_validation_without_index.md | 1 + .../rails/unique_validation_without_index.rb | 2 +- .../unique_validation_without_index_spec.rb | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_bug_unique_validation_without_index.md diff --git a/changelog/fix_bug_unique_validation_without_index.md b/changelog/fix_bug_unique_validation_without_index.md new file mode 100644 index 0000000000..0acaff7130 --- /dev/null +++ b/changelog/fix_bug_unique_validation_without_index.md @@ -0,0 +1 @@ +* [#1130](https://github.com/rubocop/rubocop-rails/issues/1130): Fix crash for `Rails/UniqueValidationWithoutIndex` with bare validate. ([@jamiemccarthy][]) diff --git a/lib/rubocop/cop/rails/unique_validation_without_index.rb b/lib/rubocop/cop/rails/unique_validation_without_index.rb index 1aa4816dd8..15aaa7758b 100644 --- a/lib/rubocop/cop/rails/unique_validation_without_index.rb +++ b/lib/rubocop/cop/rails/unique_validation_without_index.rb @@ -125,7 +125,7 @@ def class_node(node) def uniqueness_part(node) pairs = node.arguments.last - return unless pairs.hash_type? + return unless pairs&.hash_type? pairs.each_pair.find do |pair| next unless pair.key.sym_type? && pair.key.value == :uniqueness diff --git a/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb b/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb index 5994c077d7..759e1977f3 100644 --- a/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb +++ b/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb @@ -60,6 +60,24 @@ class User end RUBY end + + it 'ignores a bare validates directive by itself' do + expect_no_offenses(<<~RUBY) + class User + validates + end + RUBY + end + + it 'ignores a bare validates directive among others' do + expect_no_offenses(<<~RUBY) + class User + validates + after_commit :foo + def foo; true; end + end + RUBY + end end context 'when the table has an index but it is not unique' do