valdiates :user, presence: true
validates :user_id, presence: true
I’ve always prefered the latter as the I believe the former requires your factories to build the assocition for your tests to pass wheres the latter you can just set some arbitrary value for the id.
How about eveyone else? Are there any hard rules for choosing between the two?
I don’t know if I follow any rules, but there are some differences in behavior that I tried to document here:
In my humble opinion, validating presence of user_id misses the point at all. So the point of validating presence of association is to ensure the referenced object really exist, and we do need to create a separate user object. However, if you validate user_id instead, all can be guaranteed is that user_id is not nil or blank string, it could be any invalid id, or worse, maybe pointing to an already deleted user’s id. So I suggest never choose the second option.
Thanks @frank-west-iii I’ve took a look at the link you shared and it reinforced my understanding of the associaton validation.
@zeninpalm yes the downside to validating the presence of an id doesn’t protect you from assigining an invalid id or an id of a since deleted record. However it does offer lightweight protection against associating nothing.
I guess it depends on how complex the logic is for building or changing a model (or group of models). If theres a lot of moving parts and its possible a faulty id could be assigned it would make perfect sense to be extra cautious. But for the average controller action / operation I’m wondering how likely such a mishap would occur.
I suppose to get the best of both worlds you could employ the presence of id check in the model and in any action which requires more thorough checks use a form object to validate the association.