title: Many to many relationship to itself in PostgreSQL
body: <p>Using PostgreSQL, I have a table that should have a many to many relationship to itself. The table is called <code>tools</code> and I'm doing the many to many with a secondary table, called <code>integrations</code>, that has two fields, <code>tool_a_id</code> and <code>tool_b_id</code>.</p>
  
  <p>Is there a better way? The problem with this is that whenever I want to find all integrations I need to check for both <code>tool_a</code> and <code>tool_b</code>, as in:</p>
  
  <pre><code>SELECT * FROM integrations
  WHERE tool_a_id = x AND tool_b_id = x
  </code></pre>
  
  <p>or when I want to select all tools that integrate with another one, I have to do:</p>
  
  <pre><code>SELECT "tools".* FROM tools, integrations
  WHERE ((tools.id = integrations.tool_a_id AND integrations.tool_b_id = x) 
     OR (tools.id = integrations.tool_b_id AND integrations.tool_a_id = x))
  </code></pre>
  
  <p>This for example, doesn't allow to easily define integrations as a relationship in Rails as Rails expects one and only one foreign key to match. Is there a better way? It feels inelegant. I don't mind being stuck with PostgreSQL.</p>