diff --git a/changelog/change_restrict_duplicate_association_cop_to.md b/changelog/change_restrict_duplicate_association_cop_to.md new file mode 100644 index 0000000000..bf262d018b --- /dev/null +++ b/changelog/change_restrict_duplicate_association_cop_to.md @@ -0,0 +1 @@ +* [#994](https://github.com/rubocop/rubocop-rails/pull/994): Restrict DuplicateAssociation cop to ActiveRecord. ([@mjankowski][]) 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..91c77a344b 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 Active Record' do + it 'does not register an offense' 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