Class: RuboCop::Cop::Rails::AssociationInverseOf

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

Overview

Ensures that every ActiveRecord association (belongs_to, has_many, has_one) has an ‘inverse_of` option.

Examples:

# bad
belongs_to :user

# good
belongs_to :user, inverse_of: :posts

Constant Summary collapse

MSG =
'All associations must declare `inverse_of`.'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_configurationObject



21
22
23
24
25
26
# File 'lib/rubocop/cop/rails/association_inverse_of.rb', line 21

def self.default_configuration
  super.merge(
    'Include' => ['app/models/**/*.rb'],
    'Exclude' => ['app/serializers/**/*.rb']
  )
end

Instance Method Details

#on_send(node) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rubocop/cop/rails/association_inverse_of.rb', line 28

def on_send(node)
  return unless in_model_file?(processed_source.file_path)
  return unless association?(node)
  return if polymorphic_or_through?(node)

  kwargs = node.last_argument

  missing_inverse_of =
    !kwargs || !kwargs.hash_type? || kwargs.keys.none? { |k| k.value == :inverse_of }

  add_offense(node.loc.selector) if missing_inverse_of
rescue StandardError => e
  source_name =
    if processed_source && processed_source.buffer
      processed_source.file_path
    else
      'unknown'
    end

  warn "Rails/AssociationInverseOf failed on #{source_name}: #{e.message}"
end