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..0373fa4530 100644 --- a/lib/rubocop/cop/rails/duplicate_association.rb +++ b/lib/rubocop/cop/rails/duplicate_association.rb @@ -21,12 +21,12 @@ module Rails # has_one :foo # # # bad - # belongs_to :foo, class_name: 'Foo' - # belongs_to :bar, class_name: 'Foo' + # has_many :foo, class_name: 'Foo' + # has_many :bar, class_name: 'Foo' # has_one :baz # # # good - # belongs_to :bar, class_name: 'Foo' + # has_many :bar, class_name: 'Foo' # has_one :foo # class DuplicateAssociation < Base @@ -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