Ensure that a foreign key is always set.

cherry-pick 737f199a94ef75f294571b206ce77ff094731205
modify code to avoid using relations for Rails backwards compatibility