Skip to content

Commit

Permalink
Restrict DuplicateAssociation cop to ActiveRecord
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mjankowski committed Jul 19, 2023
1 parent b040d84 commit bc81740
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/change_restrict_duplicate_association_cop_to.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#994](https://github.com/rubocop/rubocop-rails/pull/994): Restrict DuplicateAssociation cop to ActiveRecord. ([@mjankowski][])
3 changes: 3 additions & 0 deletions lib/rubocop/cop/rails/duplicate_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class DuplicateAssociation < Base
include RangeHelp
extend AutoCorrector
include ClassSendNodeHelper
include ActiveRecordHelper

MSG = "Association `%<name>s` is defined multiple times. Don't repeat associations."

Expand All @@ -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|
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/duplicate_association_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit bc81740

Please sign in to comment.