title: Rails belongs_to not validating id when optional
body: <p>I'm running Rails 5.1.4, and I have a model that looks like this:</p>
  
  <pre><code>class Quota &lt; ActiveRecord::Base
    belongs_to :domain, optional: true
    belongs_to :project, optional: true
  end
  </code></pre>
  
  <p>A quota should belong to a domain OR project, but not both (hence setting <code>optional: true</code>).</p>
  
  <p>However, I can't seem to figure out how to make rails throw errors if an invalid project or domain ID is provided.</p>
  
  <p>Here's what happens:</p>
  
  <pre><code>q = Quota.create!(domain_id: nil, project_id: 'invalid_id')
  q.project_id # -&gt; nil
  </code></pre>
  
  <p>Even if I explicitly pass a project_id, it just magically clears it if it doesn't match a valid project.
  I tried adding a custom validation method, but by the time the validation method is called, it has already been set to nil. It doesn't even use the <code>project_id=</code> method either; I checked.</p>
  
  <p>Is there a way to get Rails to raise an error if the ID is invalid instead of setting it to nil? (while still allowing a nil value)</p>