Principle of Least Surprise (Astonishment), foreign keys, and Rails

In yesterday’s post, I sorted through the foreigner gem to figure out how to change the reference column (primary key) that a foreign_key maps to.

The problem here is that, unless your Rails project(s) has grown up referencing “natural” primary keys instead of the autoincremented id implicit in an ActiveRecord::Migration, avoiding creating surprise by not referring to an artificial primary key actually adds surprise: The instinct of someone reading your code will be to assume that the foreign key maps to the auto-id of the foreign model.

%d bloggers like this: