简体   繁体   English

Rails Foreigner:使用MySQL的“测试”数据库的外键约束

[英]Rails Foreigner: foreign key constraints for “test” DB using MySQL

I'm trying to use Foreigner to enable foreign key constraints in Rails. 我正在尝试使用Foreigner在Rails中启用外键约束。 It's working on my development DB, but I get the following error when I try to run my tests: 它正在开发数据库上运行,但是在尝试运行测试时出现以下错误:

Errors running test:units! #<ActiveRecord::StatementInvalid: Mysql2::Error: Can't create table 
'arizona_test.#sql-368_be' (errno: 150): ALTER TABLE `arizona_downloads` ADD CONSTRAINT 
`arizona_downloads_ibfk_1` FOREIGN KEY (`books_id`) REFERENCES `books`(id) ON DELETE SET NULL>

Oddly, the tests run fine, and I get this error at the end. 奇怪的是,测试运行正常,最后我得到了这个错误。

I suspect that Foreigner is trying to use SQLite syntax for the test DB, unaware that I am using MySQL (and the mysql2 adapter). 我怀疑Foreigner试图在测试数据库中使用SQLite语法,却没有意识到我正在使用MySQL(和mysql2适配器)。 Is there a way to tell Foreigner that I'm using MySQL for the test database? 有没有办法告诉Foreigner我正在将MySQL用于测试数据库?

Looking more closely, I see this is showing an MySQL errno 150. And running SHOW ENGINE INNODB STATUS showed: 仔细观察,我看到这显示的是MySQL errno150。运行SHOW ENGINE INNODB STATUS显示:

120808 11:24:29 Error in foreign key constraint of table arizona_test/#sql-368_6e:
 FOREIGN KEY (`book_id`) REFERENCES `books`(id) ON DELETE SET NULL:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.

It was happening because my development environment was using bigint(20) for ids, whereas schema.rb has int(11), due to a migration that relied on Rails' default id size. 之所以发生这种情况,是因为我的开发环境使用bigint(20)作为id,而schema.rb具有int(11),这是由于迁移依赖于Rails的默认id大小。

To solve this I changed the default primary key column type , and re-did my migrations. 为了解决这个问题,我更改了默认的主键列类型 ,然后重新进行了迁移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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