Two Foreign Keys raise "Can' create table" on MySQL AUTO_INCREMENT PRIMARY KEY

65 views Asked by At

I've created a migration file with following content.. It works fine with SQLite but when I switch to MySQL I get an "Can't create table" error (see below).

class CreateVisits < ActiveRecord::Migration[5.0]
  def change
    create_table :visits, :primary_key => :id do |t|
      t.references :user, foreign_key: true
      t.references :visitor, foreign_key: "User"
      t.timestamps
    end
    add_index :visits, [:user_id, :visitor_id], unique: true
  end
end

MySQL throws an error:

Mysql2::Error: Can't create table 'myapp_development.visits' (errno: 150): 
CREATE TABLE `visits` (
`id` int AUTO_INCREMENT PRIMARY KEY, 
`user_id` int, 
`visitor_id` int, 
`created_at` datetime NOT NULL, 
`updated_at` datetime NOT NULL,  
INDEX `index_visits_on_user_id`  (`user_id`),  
INDEX `index_visits_on_visitor_id`  (`visitor_id`), 
CONSTRAINT `fk_rails_09e5e7c20b`
FOREIGN KEY (`user_id`)
  REFERENCES `users` (`id`), 
CONSTRAINT `fk_rails_b156c396f4`
FOREIGN KEY (`visitor_id`)
  REFERENCES `visitors` (`id`)
) 

ENGINE=InnoDB

Ideas welcome!

1

There are 1 answers

0
Edmund Lee On BEST ANSWER

150 error is usually raised when you try to reference a table that doesn't exist.

In your case, you are referencing both foreign keys to the same primary key in the users table.

But you can't just use foreign_key: true in this case. But you can do it by adding two more lines

def change
  create_table :visits, :primary_key => :id do |t|
    t.references :user, references: :visits
    t.references :visitor, references: :visits
    t.timestamps
  end

  add_foreign_key :visits, :users, column: :user_id
  add_foreign_key :visits, :users, column: :visitor_id
end