I’ve always wondered which argument pass to validates method for model which hash belongs_to association: association name or field name (Rails names it as a foreign_key). Do you know? Have you ever been asked this question? I know the answer for this question and of course I will share my idea with you in this post.
Association name of foreign key?
Assume we have to models:
User. Account has mane users and user belongs to account. The code below:
We want to add validation for user to check if account is presented. And it can be achieved with two ways:
- We can add user User class presence validator for association name:
- Or we can add presence valitator for foreign key:
Which way do you use? Do you know what is difference between them? Let’s check it in rails console.
1.1. Foreign key way
This test shows us one idea - presence validator for foreign key don’t care about record existence. It means that you are able to pass account_id from form (for example, or API) with any value and ActiveRecord will save it silently. It’s obvious that it’s a hole in the application! Let’s say now what happens with second approach.
Association name way
This approach obviously is more robust - this validation cares about associated object existence, foreign key presence and also automatically validated associated object.
As you see 1st approach can bring the security issue and database inconsistency. So the answer is the following: use association name for presence validator.