Question

I'm trying to use Foreigner to enable foreign key constraints in 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). Is there a way to tell Foreigner that I'm using MySQL for the test database?

Was it helpful?

Solution

Looking more closely, I see this is showing an MySQL errno 150. And running SHOW ENGINE INNODB STATUS showed:

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.

To solve this I changed the default primary key column type, and re-did my migrations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top