From 98059c33816c4a6b46eef772c5940302d87f6d20 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sat, 8 May 2021 05:42:10 +0900 Subject: [PATCH] [Fix #419] Fix an error for `Rails/UniqueValidationWithoutIndex` Fixes #419. This PR fixes an error for `Rails/UniqueValidationWithoutIndex` when using a unique index and `check_constraint` that has `nil` first argument. --- CHANGELOG.md | 4 ++++ lib/rubocop/rails/schema_loader/schema.rb | 2 +- .../unique_validation_without_index_spec.rb | 20 +++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 99581ba47e..6ed226d737 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#419](https://github.com/rubocop/rubocop-rails/issues/419): Fix an error for `Rails/UniqueValidationWithoutIndex` when using a unique index and `check_constraint` that has `nil` first argument. ([@koic][]) + ## 2.10.1 (2021-05-06) ### Bug fixes diff --git a/lib/rubocop/rails/schema_loader/schema.rb b/lib/rubocop/rails/schema_loader/schema.rb index c641a0ebd8..8c9b62022f 100644 --- a/lib/rubocop/rails/schema_loader/schema.rb +++ b/lib/rubocop/rails/schema_loader/schema.rb @@ -114,7 +114,7 @@ class Column attr_reader :name, :type, :not_null def initialize(node) - @name = node.first_argument.value + @name = node.first_argument.str_content @type = node.method_name @not_null = nil 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 f00dc3f459..27e49cb156 100644 --- a/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb +++ b/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb @@ -89,6 +89,26 @@ class User end end + context 'with a unique index and `check_constraint` that has `nil` first argument' do + let(:schema) { <<~RUBY } + ActiveRecord::Schema.define(version: 2020_02_02_075409) do + create_table "users", force: :cascade do |t| + t.string "account", null: false + t.index ["account"], name: "index_users_on_account", unique: true + t.check_constraint nil, 'expression', name: "constraint_name" + end + end + RUBY + + it 'does not register an offense' do + expect_no_offenses(<<~RUBY) + class User + validates :account, uniqueness: true + end + RUBY + end + end + context 'when the validation is for two columns' do context 'without proper index' do let(:schema) { <<~RUBY }