Class: Rubocop::Cop::ActiveRecordDependent

Inherits:
RuboCop::Cop::Base
  • Object
show all
Defined in:
lib/rubocop/cop/active_record_dependent.rb

Overview

Cop that prevents the use of ‘dependent: …` in ActiveRecord models.

Examples:

# bad
belongs_to :foo, dependent: :destroy

# good
belongs_to :foo # With database foreign key with cascading deletes

Constant Summary collapse

MSG =
'Do not use `dependent:` to remove associated data, ' \
'use foreign keys with cascading deletes instead.'
RESTRICT_ON_SEND =
%i[has_many has_one belongs_to].to_set.freeze
ALLOWED_OPTIONS =
%i[restrict_with_error].freeze

Instance Method Summary collapse

Instance Method Details

#dependent_use(node) ⇒ Object



20
21
22
# File 'lib/rubocop/cop/active_record_dependent.rb', line 20

def_node_matcher :dependent_use, <<~PATTERN
  (send _ %RESTRICT_ON_SEND ... (hash <$(pair (sym :dependent) (sym $_)) ...>))
PATTERN

#on_send(node) ⇒ Object



24
25
26
27
28
# File 'lib/rubocop/cop/active_record_dependent.rb', line 24

def on_send(node)
  dependent_use(node) do |pair, value|
    add_offense(pair) unless ALLOWED_OPTIONS.include?(value)
  end
end