Skip to content

Commit

Permalink
Merge pull request #1170 from koic/fix_a_false_positive_for_rails_dup…
Browse files Browse the repository at this point in the history
…licate_association

[Fix #1145] Fix a false positive for `Rails/DuplicateAssociation`
  • Loading branch information
koic committed Oct 28, 2023
2 parents 6a60514 + c777a99 commit a721338
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 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][])
9 changes: 5 additions & 4 deletions lib/rubocop/cop/rails/duplicate_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down 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 a721338

Please sign in to comment.