rubocop-rails icon indicating copy to clipboard operation
rubocop-rails copied to clipboard

Rails/HasManyOrHasOneDependent false positive when `has_one` called on a class instance

Open estraph opened this issue 2 years ago • 0 comments

When defining a decorator of a model we sometimes call has_one or has_many on the base class we are decorating:

module Foo
  def self.prepended(base)
    base.has_one :bar, dependent: :destroy
  end
end

Bar.prepend(Foo)

The Rails/HasManyOrHasOneDependent cop still triggers, which seems like a false positive:

app/models/foo.rb:3:10: C: Rails/HasManyOrHasOneDependent: Specify a :dependent option.
      base.has_one :bar, dependent: :destroy
           ^^^^^^^

Expected behavior

The cop should detect that dependent: :destroy is already defined.

Actual behavior

The cop fails suggesting dependent: :destroy is not present.

Steps to reproduce the problem

Call has_one or has_many on a class instance rather than as part of a class definition.

module Foo
  def self.prepended(base)
    base.has_one :bar, dependent: :destroy
  end
end

Bar.prepend(Foo)

RuboCop version

% bundle exec rubocop -V
1.26.1 (using Parser 3.1.1.0, rubocop-ast 1.16.0, running on ruby 3.0.3 x86_64-darwin21)
  - rubocop-performance 1.13.3
  - rubocop-rails 2.14.2

estraph avatar Mar 31 '22 20:03 estraph