title: Double join with habtm in ActiveRecord
body: <p>I have a weird situation involving the need of a double inner join. I have tried the query I need, I just don't know how to make rails do it.</p>
  
  <p><strong>The Data</strong></p>
  
  <ul>
  <li>Account (has_many :sites)</li>
  <li>Site (habtm :users, belongs_to :account)</li>
  <li>User (habtm :sites)</li>
  </ul>
  
  <p>Ignore that they are habtm or whatever, I can make them habtm or has_many :through.</p>
  
  <p>I want to be able to do</p>
  
  <pre><code>@user.accounts
  </code></pre>
  
  <p>or</p>
  
  <pre><code>@account.users
  </code></pre>
  
  <p>Then of course I should be able to do</p>
  
  <pre><code>@user.accounts &lt; @some_other_account
  </code></pre>
  
  <p>And then have @user.sites include all the sites from @some_other_account.</p>
  
  <p>I've fiddled with habtm and has_many :through but can't get it to do what I want.</p>
  
  <p>Basically I need to end up with a query like this (copied from phpmyadmin. Tested and works):</p>
  
  <pre><code>SELECT accounts.* 
  FROM accounts
  INNER JOIN sites ON sites.account_id = accounts.id
  INNER JOIN user_sites ON sites.id = user_sites.site_id
  WHERE user_sites.user_id = 2
  </code></pre>
  
  <p>Can I do this? Is it even a good idea to have this double join? I am assuming it would work better if users had the association with accounts to begin with, and then worry about getting @user.sites instead, but it works better for many other things if it is kept the way it is (users &lt;-> sites).</p>