Skip to content

Commit bc81740

Browse files
committed
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.
1 parent b040d84 commit bc81740

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#994](https://github.com/rubocop/rubocop-rails/pull/994): Restrict DuplicateAssociation cop to ActiveRecord. ([@mjankowski][])

lib/rubocop/cop/rails/duplicate_association.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ class DuplicateAssociation < Base
2424
include RangeHelp
2525
extend AutoCorrector
2626
include ClassSendNodeHelper
27+
include ActiveRecordHelper
2728

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

@@ -32,6 +33,8 @@ class DuplicateAssociation < Base
3233
PATTERN
3334

3435
def on_class(class_node)
36+
return unless active_record?(class_node.parent_class)
37+
3538
offenses(class_node).each do |name, nodes|
3639
nodes.each do |node|
3740
add_offense(node, message: format(MSG, name: name)) do |corrector|

spec/rubocop/cop/rails/duplicate_association_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,4 +227,15 @@ class Post < ApplicationRecord
227227
RUBY
228228
end
229229
end
230+
231+
describe 'a class that does not descend from Active Record' do
232+
it 'does not register an offense' do
233+
expect_no_offenses(<<-RUBY)
234+
class Post < ActiveModel::Serializer
235+
has_many :comments, key: :remarks, if: :formal_mode?
236+
has_many :comments, key: :rejoinders, if: :debate_mode?
237+
end
238+
RUBY
239+
end
240+
end
230241
end

0 commit comments

Comments
 (0)