Exception: ActiveRecord::MismatchedForeignKey

Inherits:
StatementInvalid show all
Defined in:
activerecord/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, query_parser: nil) ⇒ MismatchedForeignKey

Returns a new instance of MismatchedForeignKey.



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'activerecord/lib/active_record/errors.rb', line 197

def initialize(
  message: nil,
  sql: nil,
  binds: nil,
  table: nil,
  foreign_key: nil,
  target_table: nil,
  primary_key: nil,
  primary_key_column: nil,
  query_parser: nil
)
  @original_message = message
  @query_parser = query_parser

  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

Instance Method Details

#set_query(sql, binds) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'activerecord/lib/active_record/errors.rb', line 232

def set_query(sql, binds)
  if @query_parser && !@sql
    self.class.new(
      message: @original_message,
      sql: sql,
      binds: binds,
      **@query_parser.call(sql)
    ).tap do |exception|
      exception.set_backtrace backtrace
    end
  else
    super
  end
end