Skip to content

Commit a721338

Browse files
authored
Merge pull request #1170 from koic/fix_a_false_positive_for_rails_duplicate_association
[Fix #1145] Fix a false positive for `Rails/DuplicateAssociation`
2 parents 6a60514 + c777a99 commit a721338

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1145](https://github.com/rubocop/rubocop-rails/issues/1145): Fix a false positive for `Rails/DuplicateAssociation` when using duplicate `belongs_to` associations of same class without other arguments. ([@koic][])

lib/rubocop/cop/rails/duplicate_association.rb

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@ module Rails
2121
# has_one :foo
2222
#
2323
# # bad
24-
# belongs_to :foo, class_name: 'Foo'
25-
# belongs_to :bar, class_name: 'Foo'
24+
# has_many :foo, class_name: 'Foo'
25+
# has_many :bar, class_name: 'Foo'
2626
# has_one :baz
2727
#
2828
# # good
29-
# belongs_to :bar, class_name: 'Foo'
29+
# has_many :bar, class_name: 'Foo'
3030
# has_one :foo
3131
#
3232
class DuplicateAssociation < Base
@@ -87,7 +87,8 @@ def duplicated_association_name_nodes(association_nodes)
8787
end
8888

8989
def duplicated_class_name_nodes(association_nodes)
90-
grouped_associations = association_nodes.group_by do |node|
90+
filtered_nodes = association_nodes.reject { |node| node.method?(:belongs_to) }
91+
grouped_associations = filtered_nodes.group_by do |node|
9192
arguments = association(node).last
9293
next unless arguments.count == 1
9394

spec/rubocop/cop/rails/duplicate_association_spec.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ class Post < ApplicationRecord
210210
RUBY
211211
end
212212

213-
it 'registers offenses when using duplicate associations of same class without other arguments' do
213+
it 'registers offenses when using duplicate `has_*` associations of same class without other arguments' do
214214
expect_offense(<<~RUBY)
215215
class Post < ApplicationRecord
216216
has_many :foos, class_name: 'Foo'
@@ -234,6 +234,15 @@ class Post < ApplicationRecord
234234
RUBY
235235
end
236236

237+
it 'does not register an offenses when using duplicate `belongs_to` assocs of same class without other args' do
238+
expect_no_offenses(<<~RUBY)
239+
class Post < ApplicationRecord
240+
belongs_to :foos, class_name: 'Foo'
241+
belongs_to :bars, class_name: 'Foo'
242+
end
243+
RUBY
244+
end
245+
237246
it 'does not register an offense when using duplicate associations of same class with other arguments' do
238247
expect_no_offenses(<<~RUBY)
239248
class Post < ApplicationRecord

0 commit comments

Comments
 (0)