title: Efficient ActiveRecord has_and_belongs_to_many query
body: <p>I have Page and Paragraph models with a has_and_belongs_to_many relation. Given a paragraph_id, I'd like to get all matching pages. e.g.:</p>
  
  <pre><code>pages = Paragraph.find(paragraph_id).pages.all
  </code></pre>
  
  <p>However, this takes two queries. It can be done in one query:</p>
  
  <pre><code>SELECT "pages".* FROM "pages" 
  INNER JOIN "pages_paragraphs" ON "pages_paragraphs"."page_id" = "pages"."id" 
  WHERE "pages_paragraphs"."paragraph_id" = 123
  </code></pre>
  
  <p>But can this be done without </p>
  
  <ul>
  <li>using find_by_sql</li>
  <li>without modifications to the page_paragraphs table (e.g. adding an id).</li>
  </ul>
  
  <p>Update:</p>
  
  <p>My page model looks like this:</p>
  
  <pre><code>class Page &lt; ActiveRecord::Base
    has_and_belongs_to_many :paragraphs, uniq: true
  end
  </code></pre>