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,

FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX (role_id),
INDEX (user_id)
) ENGINE = INNODB
}
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
begin
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
end
ensure
ActiveRecord::Migration.verbose = verbose
end
end
end
end
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.

Comments

jjinux said…
If I wanted to use a plugin instead of straight SQL, this is the one that looked the most promising: http://github.com/matthuhiggins/foreigner/tree/master
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.
jjinux said…
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.
jjinux said…
Thanks. I'll give it a shot.
jjinux said…
Yeah, foreigner, http://github.com/matthuhiggins/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!

Popular posts from this blog

Drawing Sierpinski's Triangle in Minecraft Using Python

In his keynote at PyCon, Eben Upton, the Executive Director of the Rasberry Pi Foundation, mentioned that not only has Minecraft been ported to the Rasberry Pi, but you can even control it with Python . Since four of my kids are avid Minecraft fans, I figured this might be a good time to teach them to program using Python. So I started yesterday with the goal of programming something cool for Minecraft and then showing it off at the San Francisco Python Meetup in the evening. The first problem that I faced was that I didn't have a Rasberry Pi. You can't hack Minecraft by just installing the Minecraft client. Speaking of which, I didn't have the Minecraft client installed either ;) My kids always play it on their Nexus 7s. I found an open source Minecraft server called Bukkit that "provides the means to extend the popular Minecraft multiplayer server." Then I found a plugin called RaspberryJuice that implements a subset of the Minecraft Pi modding API for B

Ubuntu 20.04 on a 2015 15" MacBook Pro

I decided to give Ubuntu 20.04 a try on my 2015 15" MacBook Pro. I didn't actually install it; I just live booted from a USB thumb drive which was enough to try out everything I wanted. In summary, it's not perfect, and issues with my camera would prevent me from switching, but given the right hardware, I think it's a really viable option. The first thing I wanted to try was what would happen if I plugged in a non-HiDPI screen given that my laptop has a HiDPI screen. Without sub-pixel scaling, whatever scale rate I picked for one screen would apply to the other. However, once I turned on sub-pixel scaling, I was able to pick different scale rates for the internal and external displays. That looked ok. I tried plugging in and unplugging multiple times, and it didn't crash. I doubt it'd work with my Thunderbolt display at work, but it worked fine for my HDMI displays at home. I even plugged it into my TV, and it stuck to the 100% scaling I picked for the othe

Creating Windows 10 Boot Media for a Lenovo Thinkpad T410 Using Only a Mac and a Linux Machine

TL;DR: Giovanni and I struggled trying to get Windows 10 installed on the Lenovo Thinkpad T410. We struggled a lot trying to create the installation media because we only had a Mac and a Linux machine to work with. Everytime we tried to boot the USB thumb drive, it just showed us a blinking cursor. At the end, we finally realized that Windows 10 wasn't supported on this laptop :-/ I've heard that it took Thomas Edison 100 tries to figure out the right material to use as a lightbulb filament. Well, I'm no Thomas Edison, but I thought it might be noteworthy to document our attempts at getting it to boot off a USB thumb drive: Download the ISO. Attempt 1: Use Etcher. Etcher says it doesn't work for Windows. Attempt 2: Use Boot Camp Assistant. It doesn't have that feature anymore. Attempt 3: Use Disk Utility on a Mac. Erase a USB thumb drive: Format: ExFAT Scheme: GUID Partition Map Mount the ISO. Copy everything from