Skip to main content

Rails: Foreign Key Constraints

I like referential integrity. Rails doesn't provide support for database-level foreign key constraints. "Agile Web Development with Rails" uses code such as the following to add foreign key constraints:
t.integer :product_id, :null => false, 
:options => "CONSTRAINT fk_line_item_products REFERENCES products(id)"
That doesn't work for me. The migration ran just fine, but when I looked at the database, the constraint wasn't present. I hate it when things fail silently!

I tried a plugin to add foreign key constraints, but I got frustrated pretty quickly. I fell back to executing plain SQL:
execute %{
CREATE TABLE roles_users (
role_id INT NOT NULL,
user_id INT NOT NULL,

INDEX (role_id),
INDEX (user_id)
The nice thing about plain SQL is that I can understand exactly what's going on. There are no layers of abstraction in my way, and if my SQL is wrong, MySQL will complain.

To be fair, MySQL's errors aren't always the most helpful. I encountered a couple of syntax errors. One was because I misspelled a column name. Another was because I put the name of the foreign key constraint in the wrong place. In both cases, I ended up with the following:
ERROR 1025 (HY000): Error on rename of './myapp_development/mymodel' to './myapp_development/#sql2-87-40c' (errno: 152)
Lovely! Oh well, at least it's better than failing silently.

Since I'm trying out test driven development, I knew I had to write a test before I could go mucking around with my schema. It turned out to be fairly hard to test that the database itself enforces a foreign key constraint. After all, Rails loves to try to enforce those constraints itself. Here's the RSpec test I ended up with:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Role do
context "the roles table" do
it "should enforce foreign key constraints in the database" do
verbose = ActiveRecord::Migration.verbose
ActiveRecord::Migration.verbose = false
result = ActiveRecord::Migration.execute("SHOW CREATE TABLE roles_users")
sql = result.fetch_row[1]
[/CONSTRAINT/, /FOREIGN KEY/, /REFERENCES/].each do |phrase|
sql.should =~ phrase
ActiveRecord::Migration.verbose = verbose
Ugh, painful. (Apparently, the silence method is only available on controllers. There's a different logger for migrations.)

Oh well. My tests pass, and I have referential integrity.


If I wanted to use a plugin instead of straight SQL, this is the one that looked the most promising:
Matthew Higgins said…
Hey - I just restarted active development on foreigner. The current thing I'm working on is extracting the foreign keys from the database so that they can be dumped to schema.rb.
That'd be nice ;) Currently, I have to ignore schema.rb by using rake db:migrate RAILS_ENV=test when migrating my test database.
Matthew Higgins said…
Foreigner now defines the foreign keys in schema.rb for both MySql and Postgresql. Seems to work well.
Thanks. I'll give it a shot.
Yeah, foreigner,, is pretty sweet. I still have a bunch of older migrations that are written in pure SQL, but foreigner automatically put the right stuff in my schema.rb file.

As far as I'm concerned, it's the right balance of useful and not too magical.

Thanks, again!