title: Rails: Return only objects where all associations meet a condition
body: <p>Setup:  Rails 3.2.18, Postgres</p>
  
  <p>I have two objects, for sake of example, call them <code>Author</code> and <code>Article</code>, with the following setup:</p>
  
  <pre><code>class Author
    has_many :articles
  
    ...
  end
  
  class Article
    belongs_to :author
  
    class &lt;&lt; self
  
      def published_over_one_year_ago
        where(arel_table[:published_at].lt(1.year.ago))
      end
  
    end
  end
  </code></pre>
  
  <p>I'm trying to find all <code>Author</code> records where <em>all</em> associated <code>Article</code> records are published over one year ago.  This code:</p>
  
  <pre><code>Author.joins(:article).merge(Article.published_over_one_year_ago)
  </code></pre>
  
  <p>... returns <code>Author</code> objects where <em>at least one</em> associated <code>Article</code> is published over one year ago, but I need <em>only</em> <code>Author</code> records where <em>all</em> associated <code>Article</code> records are over one year old.  Is this possible with arel / ActiveRecord, or do I have to use raw SQL?</p>
  
  <p>Potentially "Working" SQL Solution:</p>
  
  <pre><code>query = ERB.new(&lt;&lt;-SQL_END).result(binding)
    'author'.id in (
      select art.author_id
      from articles art
      group by art.author_id
      having sum(case (art.published_at::date &gt;= current_date) when true then 1 else 0 end) = 0 AND
        sum(case(art.published_at::date &lt; current_date) when true then 1 else 0 end) &gt; 0
    )
  SQL_END
  
  
  # The following now appears to do what I want it to do.
  Author.includes(:articles).where(query)
  </code></pre>
  
  <p><strong>UPDATE</strong> I see there's already a suggested answer using arel, which is outstanding. Anyone have a suggestion for using straight ActiveRecord, if possible?</p>