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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With