From d2e2d343392b23e143ac13a0b700351a5ee49b05 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sat, 28 Oct 2023 13:26:31 +0900 Subject: [PATCH] [Fix #1145] Fix a false positive for `Rails/DuplicateAssociation` Fixes #1145. This PR fixes a false positive for `Rails/DuplicateAssociation` when using duplicate `belongs_to` associations of same class without other arguments. --- ..._false_positive_for_rails_duplicate_association.md | 1 + lib/rubocop/cop/rails/duplicate_association.rb | 3 ++- spec/rubocop/cop/rails/duplicate_association_spec.rb | 11 ++++++++++- 3 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 changelog/fix_a_false_positive_for_rails_duplicate_association.md diff --git a/changelog/fix_a_false_positive_for_rails_duplicate_association.md b/changelog/fix_a_false_positive_for_rails_duplicate_association.md new file mode 100644 index 0000000000..684e6608c9 --- /dev/null +++ b/changelog/fix_a_false_positive_for_rails_duplicate_association.md @@ -0,0 +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][]) diff --git a/lib/rubocop/cop/rails/duplicate_association.rb b/lib/rubocop/cop/rails/duplicate_association.rb index 085b7fa925..7d13ca6958 100644 --- a/lib/rubocop/cop/rails/duplicate_association.rb +++ b/lib/rubocop/cop/rails/duplicate_association.rb @@ -87,7 +87,8 @@ def duplicated_association_name_nodes(association_nodes) end def duplicated_class_name_nodes(association_nodes) - grouped_associations = association_nodes.group_by do |node| + filtered_nodes = association_nodes.reject { |node| node.method?(:belongs_to) } + grouped_associations = filtered_nodes.group_by do |node| arguments = association(node).last next unless arguments.count == 1 diff --git a/spec/rubocop/cop/rails/duplicate_association_spec.rb b/spec/rubocop/cop/rails/duplicate_association_spec.rb index 1544e2a309..3fbe151ce2 100644 --- a/spec/rubocop/cop/rails/duplicate_association_spec.rb +++ b/spec/rubocop/cop/rails/duplicate_association_spec.rb @@ -210,7 +210,7 @@ class Post < ApplicationRecord RUBY end - it 'registers offenses when using duplicate associations of same class without other arguments' do + it 'registers offenses when using duplicate `has_*` associations of same class without other arguments' do expect_offense(<<~RUBY) class Post < ApplicationRecord has_many :foos, class_name: 'Foo' @@ -234,6 +234,15 @@ class Post < ApplicationRecord RUBY end + it 'does not register an offenses when using duplicate `belongs_to` assocs of same class without other args' do + expect_no_offenses(<<~RUBY) + class Post < ApplicationRecord + belongs_to :foos, class_name: 'Foo' + belongs_to :bars, class_name: 'Foo' + end + RUBY + end + it 'does not register an offense when using duplicate associations of same class with other arguments' do expect_no_offenses(<<~RUBY) class Post < ApplicationRecord