title: How to find a record through an association?
body: <p>There are four tables - <code>chat_rooms</code>, <code>chat_messages</code>, <code>chat_rooms_and_users</code> and <code>users</code>:</p>
  <ul>
  <li><code>chat_rooms</code> - The rooms have messages and users.</li>
  <li><code>chat_rooms_and_users</code> - Through this table users are connected to rooms.</li>
  </ul>
  <p>Each room can have two users.</p>
  <p><strong>How to find a room knowing two users?</strong></p>
  <p>I tried like this:</p>
  <pre class="lang-rb prettyprint-override"><code>room = joins(:chat_rooms_and_users)
         .find_by(
           type: ChatRoom.types[:private],
           chat_rooms_and_users: {
             user: [user_a, user_b]
           }
         )
  </code></pre>
  <pre class="lang-sql prettyprint-override"><code>SELECT &quot;chat_rooms&quot;.* FROM &quot;chat_rooms&quot; INNER JOIN &quot;chat_rooms_and_users&quot; ON &quot;chat_rooms_and_users&quot;.&quot;room_id&quot; = &quot;chat_rooms&quot;.&quot;id&quot; WHERE &quot;chat_rooms&quot;.&quot;type&quot; = $1 AND &quot;chat_rooms_and_users&quot;.&quot;user_id&quot; IN ($2, $3) LIMIT $4  [[&quot;type&quot;, 0], [&quot;user_id&quot;, 497], [&quot;user_id&quot;, 494], [&quot;LIMIT&quot;, 1]]
  </code></pre>
  <p>This bothers me in the SQL code:</p>
  <pre class="lang-sql prettyprint-override"><code>&quot;chat_rooms_and_users&quot;.&quot;room_id&quot; = &quot;chat_rooms&quot;.&quot;id&quot;
  </code></pre>
  <p>If there are no rooms, then the first room is created normally. But then there is always only the room whose ID is first than the rest.</p>