Class: RuboCop::Cop::Rails::MismatchedForeignKeyType

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

Overview

This cop checks for foreign key type mismatches in db/schema.rb. It detects when a table uses t.integer :xxx_id but the referenced table's primary key is bigint (Rails 5.1+ default).

Examples:

# bad
create_table "users", force: :cascade do |t|
  ...
end

create_table "posts", force: :cascade do |t|
  t.integer "user_id"
end

# good
create_table "users", force: :cascade do |t|
  ...
end

create_table "posts", force: :cascade do |t|
  t.bigint "user_id"
end

Constant Summary collapse

MSG =
'Use bigint for foreign keys that reference bigint primary keys.'

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ MismatchedForeignKeyType

Returns a new instance of MismatchedForeignKeyType.



33
34
35
36
# File 'lib/rubocop/cop/rails/mismatched_foreign_key_type.rb', line 33

def initialize(*args)
  super
  @table_pk_types = {}
end

Instance Method Details

#on_new_investigationObject

Called before all on_xxx callbacks are executed.



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rubocop/cop/rails/mismatched_foreign_key_type.rb', line 39

def on_new_investigation
  super

  processed_source.ast.each_node(:send) do |node|
    next unless node.method?(:create_table)

    table_name = extract_table_name(node)
    next unless table_name

    @table_pk_types[table_name] = extract_pk_type(node)
  end
end

#on_send(node) ⇒ Object



52
53
54
55
56
57
# File 'lib/rubocop/cop/rails/mismatched_foreign_key_type.rb', line 52

def on_send(node)
  return unless node.method?(:create_table)

  block = node.block_node
  check_integer_foreign_keys(block) if block
end