title: SQL Constraint on join table
body: <p>I have four tables in a PostgreSQL database:</p>
  
  <ul>
  <li><code>Company</code> </li>
  <li><code>User</code> (with a foreign key column company_id)  </li>
  <li><code>Location</code> (with a foreign key column company_id)  </li>
  <li><code>UserLocations</code> (an association table, with foreign key columns user_id and location_id)</li>
  </ul>
  
  <p>Essentially:  </p>
  
  <ul>
  <li>a company has many users and locations  </li>
  <li>a user belongs to a company and has many locations  </li>
  <li>a location belongs to a company and has many users</li>
  </ul>
  
  <p>I want to know if there is a way for the database to constrain entries in the UserLocations association table such that the referenced user and location must have an identical company_id value. I don't want a user from company A to have a location from company B.</p>
  
  <p>I can check this at my application layer (rails) but would be interested in making this a hard database level constraint if the option exists.</p>