Class: RuboCop::Cop::Rails::DuplicateAssociation

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp, ActiveRecordHelper, ClassSendNodeHelper
Defined in:
lib/rubocop/cop/rails/duplicate_association.rb

Overview

Looks for associations that have been defined multiple times in the same file.

When an association is defined multiple times on a model, Active Record overrides the previously defined association with the new one. Because of this, this cop’s autocorrection simply keeps the last of any duplicates and discards the rest.

Examples:


# bad
belongs_to :foo
belongs_to :bar
has_one :foo

# good
belongs_to :bar
has_one :foo

# bad
has_many :foo, class_name: 'Foo'
has_many :bar, class_name: 'Foo'
has_one :baz

# good
has_many :bar, class_name: 'Foo'
has_one :foo

Constant Summary collapse

MSG =
"Association `%<name>s` is defined multiple times. Don't repeat associations."
MSG_CLASS_NAME =
"Association `class_name: %<name>s` is defined multiple times. Don't repeat associations."

Constants included from ActiveRecordHelper

ActiveRecordHelper::WHERE_METHODS

Instance Method Summary collapse

Methods included from ActiveRecordHelper

#external_dependency_checksum, #foreign_key_of, #in_where?, #inherit_active_record_base?, #polymorphic?, #resolve_relation_into_column, #schema, #table_name

Methods included from ClassSendNodeHelper

#class_send_nodes

Instance Method Details

#on_class(class_node) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/rubocop/cop/rails/duplicate_association.rb', line 49

def on_class(class_node)
  return unless active_record?(class_node.parent_class)

  association_nodes = association_nodes(class_node)

  duplicated_association_name_nodes(association_nodes).each do |name, nodes|
    register_offense(name, nodes, MSG)
  end

  duplicated_class_name_nodes(association_nodes).each do |class_name, nodes|
    register_offense(class_name, nodes, MSG_CLASS_NAME)
  end
end