[英]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). 我已经创建了一个包含以下内容的迁移文件。它在SQLite上正常工作,但是当我切换到MySQL时,出现“无法创建表”错误(请参见下文)。
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: MySQL引发错误:
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. 当您尝试引用不存在的表时,通常会引发150错误。
In your case, you are referencing both foreign keys to the same primary key in the users
table. 在您的情况下,您要将两个外键都引用到
users
表中的同一主键。
But you can't just use foreign_key: true
in this case. 但是在这种情况下,您不能只使用
foreign_key: true
。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.