Class: RuboCop::Cop::DevDoc::Migration::RedundantReferenceIndex
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::DevDoc::Migration::RedundantReferenceIndex
- Extended by:
- AutoCorrector
- Includes:
- HashPairRemoval
- Defined in:
- lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb
Overview
Avoid the redundant index: true on references.
Rationale
belongs_to / references / add_reference default to
index: true since Rails 5 — the index is created whether or not
the option is written. An explicit index: true therefore does
nothing except make every future reader wonder whether it does
(and imply, wrongly, that references without it are unindexed).
The option is only meaningful when it overrides the default:
index: false to opt out, or a hash to customize
(index: { unique: true }). Those forms pass untouched.
❌ Redundant — this index exists anyway
t.belongs_to :user, foreign_key: true, null: false, index: true
✔️
t.belongs_to :user, foreign_key: true, null: false
✔️ Meaningful override
t.belongs_to :user, foreign_key: true, null: false, index: { unique: true }
NOTE: This cop removes the one reference option whose default is
already correct; the sibling cops
DevDoc/Migration/RequireReferenceForeignKey and
DevDoc/Migration/ExplicitNullOnReference require the two options
that ARE decisions to be made and stated. Together: everything
written on a reference is a decision, everything omitted is
doctrine.
NOTE: When a comment sits between the call's arguments, the cop flags the option but does not autocorrect (removing the range would corrupt the comment) — delete the option manually.
NOTE: Migrations declared < ActiveRecord::Migration[4.2] are
skipped entirely: the 4.2 compatibility layer flips the reference
default to index: false, so there index: true is meaningful —
removing it would drop the index on a from-zero db:migrate.
Constant Summary collapse
- MSG =
'`index: true` is redundant — references are indexed by default since Rails 5.'.freeze
- RESTRICT_ON_SEND =
%i[belongs_to references add_reference add_belongs_to].freeze
Instance Method Summary collapse
Instance Method Details
#on_send(node) ⇒ Object
63 64 65 66 67 68 69 |
# File 'lib/rubocop/cop/dev_doc/migration/redundant_reference_index.rb', line 63 def on_send(node) = node.arguments.find(&:hash_type?) return unless return if legacy_migration?(node) .pairs.each { |pair| check_pair(node, , pair) } end |