Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Rails Migration fails?

I'm using uuid instead of bigint as primaty key. And next migration

class CreateProjects < ActiveRecord::Migration[6.0]
  def change
    create_table :projects, id: :uuid do |t|
      t.string :title
      t.references :user, null: false, foreign_key: true
      t.timestamps
    end
  end
end

fails with error:

PG::DatatypeMismatch: ERROR:  foreign key constraint "fk_rails_b872a6760a" cannot be implemented
DETAIL:  Key columns "user_id" and "id" are of incompatible types: bigint and uuid.
like image 986
Kyryl Ωliinyk Avatar asked Dec 07 '22 10:12

Kyryl Ωliinyk


1 Answers

t.references by default assumes the other table has a bigint primary key and makes the foreign key field also a bigint. Once the foreign key is added, this discrepancy is revealed and the migration fails.

Use type: :uuid to specify that the column should indeed be a uuid.

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

I myself in my projects keep track of it by remembering that every references/belongs to needs to have 4 options. null, foreign_key, type and index. That forces me to think about each of the 4 options even if I choose to leave their values as defaults.

like image 90
Siim Liiser Avatar answered Dec 20 '22 13:12

Siim Liiser