From fa6b9d797578c0d1d243d8a0377ba67188d04a28 Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Fri, 28 Apr 2023 10:32:51 -0400 Subject: [PATCH] Restrict DuplicateAssociation cop to ActiveRecord Previously this cop would run against all classes, which led to false positives when the class was not descended from `ActiveRecord::Base` and thus might have acceptable use cases for repeating association declarations in ways that would not be acceptable in AR classes. --- lib/rubocop/cop/rails/duplicate_association.rb | 3 +++ spec/rubocop/cop/rails/duplicate_association_spec.rb | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/lib/rubocop/cop/rails/duplicate_association.rb b/lib/rubocop/cop/rails/duplicate_association.rb index 6c7b972bfb..968585fa7a 100644 --- a/lib/rubocop/cop/rails/duplicate_association.rb +++ b/lib/rubocop/cop/rails/duplicate_association.rb @@ -24,6 +24,7 @@ class DuplicateAssociation < Base include RangeHelp extend AutoCorrector include ClassSendNodeHelper + include ActiveRecordHelper MSG = "Association `%s` is defined multiple times. Don't repeat associations." @@ -32,6 +33,8 @@ class DuplicateAssociation < Base PATTERN def on_class(class_node) + return unless active_record?(class_node.parent_class) + offenses(class_node).each do |name, nodes| nodes.each do |node| add_offense(node, message: format(MSG, name: name)) do |corrector| diff --git a/spec/rubocop/cop/rails/duplicate_association_spec.rb b/spec/rubocop/cop/rails/duplicate_association_spec.rb index 43d9e0c3cf..72de685ab9 100644 --- a/spec/rubocop/cop/rails/duplicate_association_spec.rb +++ b/spec/rubocop/cop/rails/duplicate_association_spec.rb @@ -227,4 +227,15 @@ class Post < ApplicationRecord RUBY end end + + describe 'a class that does not descend from activerecord' do + it 'does not register an office' do + expect_no_offenses(<<-RUBY) + class Post < ActiveModel::Serializer + has_many :comments, key: :remarks, if: :formal_mode? + has_many :comments, key: :rejoinders, if: :debate_mode? + end + RUBY + end + end end