title: How to find posts tagged with more than one tag in Rails and Postgresql
body: <p>I have the models <code>Post</code>, <code>Tag</code>, and <code>PostTag</code>. A post has many tags through post tags. I want to find posts that are exclusively tagged with more than one tag.</p>
  
  <pre><code>has_many :post_tags
  has_many :tags, through: :post_tags
  </code></pre>
  
  <p>For example, given this data set:</p>
  
  <pre><code>posts table
  --------------------
  id | title         |
  --------------------
  1  | Carb overload |
  2  | Heart burn    |
  3  | Nice n Light  |
  
  tags table
  -------------
  id | name   |
  -------------
  1  | tomato |
  2  | potato |
  3  | basil  |
  4  | rice   |
  
  post_tags table
  -----------------------
  id | post_id | tag_id |
  -----------------------
  1  | 1       | 1      |
  2  | 1       | 2      |
  3  | 2       | 1      |
  4  | 2       | 3      |
  5  | 3       | 1      |
  </code></pre>
  
  <p>I want to find posts tagged with <code>tomato</code> AND <code>basil</code>. This should return only the "Heart burn" post (id 2). Likewise, if I query for posts tagged with <code>tomato</code> AND <code>potato</code>, it should return the "Carb overload" post (id 1).</p>
  
  <p>I tried the following:</p>
  
  <pre><code>Post.joins(:tags).where(tags: { name: ['basil', 'tomato'] })
  </code></pre>
  
  <p>SQL</p>
  
  <pre><code>SELECT "posts".* FROM "posts"
  INNER JOIN "post_tags" ON "post_tags"."post_id" = "posts"."id"
  INNER JOIN "tags" ON "tags"."id" = "post_tags"."tag_id"
  WHERE "tags"."name" IN ('basil', 'tomato')
  </code></pre>
  
  <p>This returns all three posts because all share the tag tomato. I also tried this:</p>
  
  <pre><code>Post.joins(:tags).where(tags: { name 'basil' }).where(tags: { name 'tomato' })
  </code></pre>
  
  <p>SQL</p>
  
  <pre><code>SELECT "posts".* FROM "posts"
  INNER JOIN "post_tags" ON "post_tags"."post_id" = "posts"."id"
  INNER JOIN "tags" ON "tags"."id" = "post_tags"."tag_id"
  WHERE "tags"."name" = 'basil' AND "tags"."name" = 'tomato'
  </code></pre>
  
  <p>This returns no records.</p>
  
  <p>How can I query for posts tagged with multiple tags?</p>