title: Avoiding duplicate joins in Rails ActiveRecord query
body: <p>I have a scenario where I have SQL joins somewhere in the query chain, and then at some further point I need to append a condition which needs the same join, but I don't know at this point whether that join exists already in the scope. For example:</p>
  
  <pre><code>@foo = Foo.joins("INNER JOIN foos_bars ON foos_bars.foo_id = foos.id")
  ....
  @foo.joins(:bars).where(bars: { id: 1 })
  </code></pre>
  
  <p>This will product an SQL error about duplicate table/alias names.</p>
  
  <p>The reason I write the SQL join manually in the first instance is to improve the efficiency as the classic rails AREL join will product two INNER JOINS where in my case I only need the one.</p>
  
  <p>Is there a recommended way around this? Some way to inspect the joins currently in a scope for example.</p>
  
  <p><strong>Response to comment:</strong></p>
  
  <p>With a <code>has_and_belongs_to_many</code> relationship Rails produces two <code>INNER JOINS</code> like this:</p>
  
  <pre><code>SELECT "journals".* FROM "journals"
  INNER JOIN "categories_journals"
    ON "categories_journals"."journal_id" = "journals"."id"
  INNER JOIN "categories"
    ON "categories"."id" = "categories_journals"."category_id"
  WHERE "categories"."id" = 1
  </code></pre>
  
  <p>Whereas I believe I can do this instead:</p>
  
  <pre><code>SELECT "journals".* FROM "journals"
  INNER JOIN "categories_journals"
    ON "categories_journals"."journal_id" = "journals"."id"
  WHERE "categories_journals"."category_id" = 1
  </code></pre>
  
  <p>Correct me if I'm wrong.</p>