Rails - how do I validate existence of a row referenced by foreign key

There is a plugin that helps you with this for belongs_to associations: Validates existence of. But, maybe you can add your own validation? What about something like this:

# Assuming your foreign key is user_id (which references the table User)
validate :user_id_exists

def user_id_exists
  return false if User.find_by_id(self.user_id).nil?
end

I had problems with this piece of code:

return false if User.find(self.user_id).nil?

I had to catch the ActiveRecord exception when no matching record was found. nil? does not work when no record is found; the exception is thrown before nil? is executed.

# Assuming your foreign key is user_id (which references the table User)
validate :user_id_exists

def user_id_exists
  begin
    User.find(self.user_id)
  rescue ActiveRecord::RecordNotFound
    errors.add(:user_id, "user_id foreign key must exist")
    false
  end
end

This is useful when you use invalid? assertions in unit tests.

request.user_id = unknown
assert request.invalid?

request.user_id = 1
assert request.valid?

Simply use like below,

validates :user, presence: true

It will automatically check the existence of user record in db.

Reference from the Active Record Validation - presence:

If you want to be sure that an association is present, you'll need to test whether the associated object itself is present, and not the foreign key used to map the association. This way, it is not only checked that the foreign key is not empty but also that the referenced object exists.