[Proposal] validate presence of optional association, if it's set

Maybe this is a weird one, but if you have some associations, like this:

class Arm < ApplicationRecord
  belongs_to(:body)
  belongs_to(:hand, optional: true)
end

Then you also have foreign key constraints on these columns.

Now, this is all good:

Arm.create(body_id: 1)

This creates a validation error (belongs_to is required by default)

Arm.create(body_id: 0)

This works, if Hand ID 2 exists

Arm.create(body_id: 1, hand_id: 2)

This raises an InvalidForeignKey exception since Hand ID 0 doesn’t exist

Arm.create(body_id: 1, hand_id: 0)

To avoid this, you can do something like

class Arm < ApplicationRecord
  belongs_to(:body)
  belongs_to(:hand, optional: true)

  validates(:hand, presence: true, if: :hand_id)
end

So you validate the presence of the :hand association, but only it’s set. That way you avoid the invalid foreign key error.

Would it make sense to add this as an option to belongs_to so it validates presence if it’s set?