Given that the \"Rails Way\" seems to be not to use foreign key constraints, I\'m looking for an alternative that will allow me to validate that the row a foreign key references
There is a plugin that helps you with this for belongs_to associations: Validates existence of. But, maybe you can add your own validation? What about something like this:
# Assuming your foreign key is user_id (which references the table User)
validate :user_id_exists
def user_id_exists
return false if User.find_by_id(self.user_id).nil?
end
Simply use like below,
validates :user, presence: true
It will automatically check the existence of user record in db.
Reference from the Active Record Validation - presence:
If you want to be sure that an association is present, you'll need to test whether the associated object itself is present, and not the foreign key used to map the association. This way, it is not only checked that the foreign key is not empty but also that the referenced object exists.