In Rails 3.0 (and probably in modern versions) you can ensure the validity of your models by using validations . One I use is the :presence , to make an object invalid if a variable is not present.
The problem comes when you investigate how validation is made. Each time we save the validated object is got from the database (*).
Something simple as:
will hit the database checking if user exists.
Solution: build a custom Validator and use it:
The tricky part is to check for the foreign_key BUT if this is not already set (on create), check for the relation.
This validation run on the foreign key, so we modify the code in the model.
One last note. The code for the validator must be included in some path that is automatically loaded ( read this)
(*) Note that this is a very particular case, when we check the presence of a relation. Checking for the foreign_key user_id won't work, since on creation, this foreign_key can be null