diff --git a/CHANGELOG.md b/CHANGELOG.md index b0e5459e7a..ad28ccef09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ * [#213](https://github.com/rubocop-hq/rubocop-rails/pull/213): Fix a false positive for `Rails/UniqueValidationWithoutIndex` when using conditions. ([@sunny][]) * [#215](https://github.com/rubocop-hq/rubocop-rails/issues/215): Fix a false positive for `Rails/UniqueValidationWithoutIndex` when using Expression Indexes. ([@koic][]) +* [#214](https://github.com/rubocop-hq/rubocop-rails/issues/214): Fix an error for `Rails/UniqueValidationWithoutIndex`when a table has no column definition. ([@koic][]) ## 2.5.0 (2020-03-24) diff --git a/lib/rubocop/rails/schema_loader/schema.rb b/lib/rubocop/rails/schema_loader/schema.rb index 2ba81c1c75..7057e08734 100644 --- a/lib/rubocop/rails/schema_loader/schema.rb +++ b/lib/rubocop/rails/schema_loader/schema.rb @@ -60,7 +60,7 @@ def with_column?(name:) def build_columns(node) each_content(node).map do |child| - next unless child.send_type? + next unless child&.send_type? next if child.method?(:index) Column.new(child) @@ -69,7 +69,7 @@ def build_columns(node) def build_indices(node) each_content(node).map do |child| - next unless child.send_type? + next unless child&.send_type? next unless child.method?(:index) Index.new(child) @@ -79,7 +79,7 @@ def build_indices(node) def each_content(node) return enum_for(__method__, node) unless block_given? - case node.body.type + case node.body&.type when :begin node.body.children.each do |child| yield(child) 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 68016c9248..8ddc74d1bc 100644 --- a/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb +++ b/spec/rubocop/cop/rails/unique_validation_without_index_spec.rb @@ -303,6 +303,23 @@ class Article end end + context 'when a table has no column definition' do + let(:schema) { <<~RUBY } + ActiveRecord::Schema.define(version: 2020_02_02_075409) do + create_table "users", force: :cascade do |t| + end + end + RUBY + + it 'ignores it' do + expect_no_offenses(<<~RUBY) + class User + validates :account, uniqueness: true + end + RUBY + end + end + context 'when the validation is for a relation with foreign_key: option' do context 'without proper index' do let(:schema) { <<~RUBY }