views:

44

answers:

1

What's the more accepted Rails approach?

Validate that a foreign key exists on creation/update

or

"Damage control" when we want to use the non-existent foreign key?

Initial validation requires more resources on row creation/updating, and may even be redundant when I'm creating rows systematically in my code (i.e. not user generated). However, I can smoothly write my business logic, without fear of running into bad foreign key.

And on the other hand, damage control allows for quick creation and updating, but of course, more checks and recovery in my logic.

Can you think of any other pros and cons? Perhaps there's even more alternatives than just these two doctrines.

How do experienced Rails developers handle this problem?

+1  A: 

If by validate ahead of time you mean doing an additional database request just to validate the existence of a key, I would say don't do it. We use FKs all over, and have almost never run into problems, especially not on a create or update. If it does fail, that's probably a good thing, unlike a validation you can do something about, if you just tried to add an association to a no longer existing object, that seems like a pretty good reason for an error to me.

If you have particularly volatile entities such that an instance might frequently have been deleted between the time it is instantiated and the time you try to save it in a FK, then maybe in that particular case it might be worth it, but as a general guide I would not.

I also often use FKs between tables that are deleted using logical deletes (a la acts_as_paranoid, set a deleted_at flag rather than actually delete the row), which also eases the problems of FKs failing, and I find to be a very helpful strategy at least in my app.

Andrew Kuklewicz