Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails model generation fails due to foreign key type

I created a model with the following command:

rails g model UserCertification user:references certification:references certification_no:string

which is referencing to my devise user model user:references.

On the db:migrate I receive the following error: Caused by:

ActiveRecord::MismatchedForeignKey: Column user_id on table user_certifications does not match column id on users, which has type bigint(20). To resolve this issue, change the type of the user_id column on user_certifications to be :bigint. (For example t.bigint :user_id). Original message: Mysql2::Error: Cannot add foreign key constraint

Here is my migration

class CreateUserCertifications < ActiveRecord::Migration[6.0]
  def change
    create_table :user_certifications do |t|
      t.references :user, null: false, foreign_key: true
      t.references :certification, null: false, foreign_key: true
      t.string :certification_no

      t.timestamps
    end
  end
end

I tried to set the type to integer with t.references :user, null: false, foreign_key: true,type: :integer

I also deleted the model and redid and checked with previous references, without success. Perhaps someone has an idea?

like image 276
Christian K. Avatar asked Feb 10 '20 19:02

Christian K.


1 Answers

Try setting the type in the reference to match the other table:

t.references(:user, null: false, type: :bigint)

If that doesn't work, try creating the foreign key in user_certifications explicitly:

t.bigint :user_id, null: false
t.references(:user)
like image 151
David Hempy Avatar answered Oct 15 '22 16:10

David Hempy