简体   繁体   中英

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM