Exception: ActiveRecord::MismatchedForeignKey

Inherits:
StatementInvalid show all
Defined in:
lib/active_record/errors.rb

Overview

Raised when a foreign key constraint cannot be added because the column type does not match the referenced column type.

Instance Attribute Summary

Attributes inherited from StatementInvalid

#binds, #sql

Instance Method Summary collapse

Constructor Details

#initialize(message: nil, sql: nil, binds: nil, table: nil, foreign_key: nil, target_table: nil, primary_key: nil, primary_key_column: nil) ⇒ MismatchedForeignKey

Returns a new instance of MismatchedForeignKey.



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/active_record/errors.rb', line 129

def initialize(
  message: nil,
  sql: nil,
  binds: nil,
  table: nil,
  foreign_key: nil,
  target_table: nil,
  primary_key: nil,
  primary_key_column: nil
)
  if table
    type = primary_key_column.bigint? ? :bigint : primary_key_column.type
    msg = <<~EOM.squish
      Column `#{foreign_key}` on table `#{table}` does not match column `#{primary_key}` on `#{target_table}`,
      which has type `#{primary_key_column.sql_type}`.
      To resolve this issue, change the type of the `#{foreign_key}` column on `#{table}` to be :#{type}.
      (For example `t.#{type} :#{foreign_key}`).
    EOM
  else
    msg = <<~EOM.squish
      There is a mismatch between the foreign key and primary key column types.
      Verify that the foreign key column type and the primary key of the associated table match types.
    EOM
  end
  if message
    msg << "\nOriginal message: #{message}"
  end
  super(msg, sql: sql, binds: binds)
end