From 6a4ee87f037e2336ffba80acc87cf6a1f379bc2e Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Wed, 25 Oct 2017 15:57:38 +0900 Subject: [PATCH] [Fix #4909] Make `Rails/HasManyOrHasOneDependent` aware multiple associations Fixes #4909. This commit tested and fixed the problem reproduction. --- CHANGELOG.md | 1 + .../cop/rails/has_many_or_has_one_dependent.rb | 8 ++++++-- .../rails/has_many_or_has_one_dependent_spec.rb | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 465e48049ada..b0a5b426aaaa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ * [#1583](https://github.com/bbatsov/rubocop/issues/1583): Add a quiet formatter. ([@drenmi][]) * [#4794](https://github.com/bbatsov/rubocop/issues/4794): Fix an error in `Layout/MultilineOperationIndentation` when an operation spans multiple lines and contains a ternary expression. ([@rrosenblum][]) +* [#4909](https://github.com/bbatsov/rubocop/issues/4909): Make `Rails/HasManyOrHasOneDependent` aware of multiple associations in `with_options`. ([@koic][]) ## 0.51.0 (2017-10-18) diff --git a/lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb b/lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb index 3c6ab960c9ee..e4524b5fb7a6 100644 --- a/lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb +++ b/lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb @@ -49,8 +49,12 @@ class HasManyOrHasOneDependent < Cop def on_send(node) if !association_without_options?(node) return if valid_options?(association_with_options?(node)) - elsif with_options_block(node.parent) - return if valid_options?(with_options_block(node.parent)) + else + n = node.parent.begin_type? ? node.parent.parent : node.parent + + if with_options_block(n) + return if valid_options?(with_options_block(n)) + end end add_offense(node, location: :selector) diff --git a/spec/rubocop/cop/rails/has_many_or_has_one_dependent_spec.rb b/spec/rubocop/cop/rails/has_many_or_has_one_dependent_spec.rb index 28f25c3fcac4..f1fa5ef61480 100644 --- a/spec/rubocop/cop/rails/has_many_or_has_one_dependent_spec.rb +++ b/spec/rubocop/cop/rails/has_many_or_has_one_dependent_spec.rb @@ -113,6 +113,20 @@ class Person end RUBY end + + context 'Multiple associations' do + it "doesn't register an offense for " \ + '`with_options dependent: :destroy`' do + expect_no_offenses(<<-RUBY.strip_indent) + class Person + with_options dependent: :destroy do + has_many :foo + has_many :bar + end + end + RUBY + end + end end end end