title: ActiveRecord/Postgres: aggregate functions are not allowed in WHERE
body: <p>I want to retrieve contacts, which have many activities, where the max completed_date of the latter was 6 months ago. Let me ilustrate it:</p>
  
  <pre><code>user = User.first
  user.contacts.first.activities.maximum(:completed_date)
  # SELECT MAX("activities"."completed_date") AS max_id FROM "activities" WHERE "activities"."user_id" = $1  [["user_id", 12]]
  =&gt; 2014-03-18 09:06:54 UTC
  </code></pre>
  
  <p>Thats perfect. Now I want to use that a clause for a WHERE query but it seems I can't:</p>
  
  <pre><code>user.contacts.joins(:activities)
    .where('MAX("activities"."completed_date") &lt; ?', Time.now - 6.months)
  # SELECT "contacts".* FROM "contacts"
  # INNER JOIN "activities" ON "activities"."contact_id" = "contacts"."id"
  # WHERE "contacts"."user_id" = $1 AND (MAX("activities"."completed_date") &lt;= '2013-09-23 05:55:21.191254')  [["user_id", 12]]
  
  #=&gt; PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
  #   LINE 1: ...ntacts"."id" WHERE "contacts"."user_id" = $1 AND (MAX("activ...
  </code></pre>
  
  <p>How I'm supposed to do this?</p>