Rails Foreigner:使用MySQL“测试”DB的外键约束

时间:2012-08-08 14:17:12

标签: ruby-on-rails-3 activerecord foreigner

我正在尝试使用Foreigner在Rails中启用外键约束。它正在我的开发数据库上工作,但是当我尝试运行我的测试时出现以下错误:

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>

奇怪的是,测试运行正常,最后我得到了这个错误。

我怀疑Foreigner正在尝试将SQLite语法用于测试数据库,而不知道我正在使用MySQL(以及mysql2适配器)。有没有办法告诉外国人我正在使用MySQL作为测试数据库?

1 个答案:

答案 0 :(得分:0)

仔细观察,我看到这显示了一个MySQL errno 150.并且运行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.

之所以发生这种情况,是因为我的开发环境使用bigint(20)表示id,而schema.rb使用int(11),因为迁移依赖于Rails的默认id大小。

要解决此问题,我更改了default primary key column type,并重新进行了迁移。