Class: RuboCop::Cop::DevDoc::Migration::PreferBelongsTo

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/dev_doc/migration/prefer_belongs_to.rb

Overview

Prefer ‘t.belongs_to` over `t.references` for foreign keys.

## Rationale ‘t.belongs_to` and `t.references` are aliases and functionally identical. Prefer `belongs_to` because it matches the model’s association declaration (‘belongs_to :user`), which makes the migration easier to map to the model and improves readability.


t.references :user, foreign_key: true, null: false

✔️
t.belongs_to :user, foreign_key: true, null: false

Examples:

# bad
t.references :user, foreign_key: true, null: false

# good
t.belongs_to :user, foreign_key: true, null: false

Constant Summary collapse

MSG =
'Use `t.belongs_to` instead of `t.references` ' \
'(aliases, but `belongs_to` matches the model association).'.freeze
RESTRICT_ON_SEND =
%i[references].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



32
33
34
35
36
# File 'lib/rubocop/cop/dev_doc/migration/prefer_belongs_to.rb', line 32

def on_send(node)
  add_offense(node.loc.selector) do |corrector|
    corrector.replace(node.loc.selector, 'belongs_to')
  end
end