Skip to content

Commit

Permalink
[Fix rubocop#1145] Fix a false positive for Rails/DuplicateAssociation
Browse files Browse the repository at this point in the history
Fixes rubocop#1145.

This PR fixes a false positive for `Rails/DuplicateAssociation`
when using duplicate `belongs_to` associations of same class without other arguments.
  • Loading branch information
koic committed Oct 28, 2023
1 parent 6a60514 commit d2e2d34
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -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][])
3 changes: 2 additions & 1 deletion lib/rubocop/cop/rails/duplicate_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

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

0 comments on commit d2e2d34

Please sign in to comment.