Class: RuboCop::Cop::Rails::HasManyOrHasOneDependent

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb

Overview

Looks for ‘has_many` or `has_one` associations that don’t specify a ‘:dependent` option.

It doesn’t register an offense if ‘:through` or `dependent: nil` is specified, or if the model is read-only.

Examples:

# bad
class User < ActiveRecord::Base
  has_many :comments
  has_one :avatar
end

# good
class User < ActiveRecord::Base
  has_many :comments, dependent: :restrict_with_exception
  has_one :avatar, dependent: :destroy
  has_many :articles, dependent: nil
  has_many :patients, through: :appointments
end

class User < ActiveRecord::Base
  has_many :comments
  has_one :avatar

  def readonly?
    true
  end
end

Constant Summary collapse

MSG =
'Specify a `:dependent` option.'
RESTRICT_ON_SEND =
%i[has_many has_one].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/rubocop/cop/rails/has_many_or_has_one_dependent.rb', line 78

def on_send(node)
  return if active_resource?(node.parent) || readonly_model?(node)
  return if !association_without_options?(node) && valid_options?(association_with_options?(node))
  return if valid_options_in_with_options_block?(node)

  add_offense(node.loc.selector)
end