diff --git a/CHANGELOG.md b/CHANGELOG.md index 14009c16af..5f07879ea2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#535](https://github.com/rubocop/rubocop-rails/issues/535): Fix an error for `Rails/HasManyOrHasOneDependent` when using lambda argument and not specifying any options. ([@koic][]) + ## 2.12.0 (2021-09-09) ### New features 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 3a6d5aed22..432d25721c 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 @@ -100,8 +100,8 @@ def valid_options_in_with_options_block?(node) end def contain_valid_options_in_with_options_block?(node) - if with_options_block(node) - return true if valid_options?(with_options_block(node)) + if (options = with_options_block(node)) + return true if valid_options?(options) return false unless node.parent @@ -114,6 +114,8 @@ def contain_valid_options_in_with_options_block?(node) end def valid_options?(options) + return false if options.nil? + options = options.first.children.first.pairs if options.first.kwsplat_type? return true unless options 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 b22e4013df..ca7fbf754e 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 @@ -20,6 +20,15 @@ class Person < ApplicationRecord RUBY end + it 'registers an offense when using lambda argument and not specifying any options' do + expect_offense(<<~RUBY) + class User < ApplicationRecord + has_one :articles, -> { where(active: true) } + ^^^^^^^ Specify a `:dependent` option. + end + RUBY + end + it 'does not register an offense when specifying `:dependent` strategy' do expect_no_offenses(<<~RUBY) class Person < ApplicationRecord