Hi guys, how to validate a Rails belongs_to association in most effective way? Did you think about this anytime? I am asking this question because there is something that most of the people will not notice. I will explain here.
Suppose we have 2 Models User and Group
Every User must belongs to one of the group.
So how we validate this? The normal way that everyone follows is given below.
Validate foreign key
class User belongs_to group validates :group_id, presence: true end
What this code actually does? Lets find out.
> Group.last.id # => 80 > User.new(group_id: 100).valid? # => true > Group.exists?(100) # => nil
Whats that? Is it true? Not really. So rails fooling us? Haha. The presence validator for foreign key will only check system provides any value to it. Thats it. And it is not cared about the existence of that record. So what we will do for that? Lets check the second method.
Validate associated record
class User belongs_to group validates :group, presence: true end
Here what the validator does is in the background it checks the record exists or not. If record not exists it returns false for valid? method.
> Group.last.id # => 80 > user = User.new(group_id: 100) > user.valid? # => false > Group.exists?(100) # => nil > user.errors.full_messages # => ["Group can't be blank"]
Wahh..great! But wait…think… What it actually does? Whenever the user record goes through the valid? method, in the background rails fire a query to the database to find this record exists or not. Is that good? In some way, it is bad. It affects performance.
But we have to consider database integrity. So the second approach wins even though it is firing an extra query in the background.