Skip to content

Commit cc74d55

Browse files
committed
Fix Rails/HasManyOrHasOneDependent to correctly handle association methods with receiver
1 parent 0449e6d commit cc74d55

File tree

3 files changed

+36
-11
lines changed

3 files changed

+36
-11
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#687](https://github.com/rubocop/rubocop-rails/issues/687): Fix `Rails/HasManyOrHasOneDependent` to correctly handle association methods with receiver. ([@fatkodima][])

lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ class HasManyOrHasOneDependent < Base
4141
PATTERN
4242

4343
def_node_matcher :association_without_options?, <<~PATTERN
44-
(send nil? {:has_many :has_one} _)
44+
(send _ {:has_many :has_one} _)
4545
PATTERN
4646

4747
def_node_matcher :association_with_options?, <<~PATTERN
48-
(send nil? {:has_many :has_one} ... (hash $...))
48+
(send _ {:has_many :has_one} ... (hash $...))
4949
PATTERN
5050

5151
def_node_matcher :dependent_option?, <<~PATTERN

spec/rubocop/cop/rails/has_many_or_has_one_dependent_spec.rb

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -241,17 +241,41 @@ class Person < ActiveRecord::Base
241241
RUBY
242242
end
243243

244-
it 'registers an offense when using mix-in module that has an association of Active Record' do
245-
expect_offense(<<~RUBY)
246-
module Foo
247-
extend ActiveSupport::Concern
244+
context 'mix-in module' do
245+
it 'registers an offense when has an association of Active Record' do
246+
expect_offense(<<~RUBY)
247+
module Foo
248+
extend ActiveSupport::Concern
248249
249-
included do
250-
has_many :bazs
251-
^^^^^^^^ Specify a `:dependent` option.
250+
included do
251+
has_many :bazs
252+
^^^^^^^^ Specify a `:dependent` option.
253+
end
252254
end
253-
end
254-
RUBY
255+
RUBY
256+
end
257+
258+
it 'registers an offense when association method is called on the base class and no `:dependent` strategy' do
259+
expect_offense(<<~RUBY)
260+
module Foo
261+
def self.included(base)
262+
base.has_many :bazs
263+
^^^^^^^^ Specify a `:dependent` option.
264+
end
265+
end
266+
RUBY
267+
end
268+
269+
it 'does not register an offense when association method is called on the base class' \
270+
'and has `:dependent` strategy' do
271+
expect_no_offenses(<<~RUBY)
272+
module Foo
273+
def self.included(base)
274+
base.has_many :bazs, dependent: :destroy
275+
end
276+
end
277+
RUBY
278+
end
255279
end
256280

257281
it 'does not register an offense when using associations of Active Resource' do

0 commit comments

Comments
 (0)