title: How to avoid a race condition when validating uniqueness across two tables in Rails
body: <p><a href="https://stackoverflow.com/questions/21012826/validating-uniqueness-across-two-tables">This question</a> discusses validating uniqueness across two tables, and the accepted answer mentions "that such code level unique constraints may not work in a race condition among parallel requests unless somehow this can be done at database level."</p>
  
  <p>That is, if you have a <code>User</code> and an <code>Organization</code> and were to validate a unique <code>slug</code> across both, how do you ensure this at the database level, or otherwise avoid the possibility of a race condition arising?</p>
  
  <p>My only thought would be to create a related record like <code>Slug</code>, which <code>belongs_to</code> both models. You would wrap <code>create</code> and <code>update</code> of these models in a transaction where you also create the associated record. This record isn't used for anything except ensuring the additional uniqueness constraint and raising an error at the database level if this is violated.</p>
  
  <p>Is there a better approach or am I on the right path?</p>