title: Rails - ActiveRecord query - Find first item where relationship.count at least 1
body: <p>I have two models:</p>
  
  <pre><code>class Post &lt; ActiveRecord::Base
    has_many :comments
  end
  
  class Comment &lt; ActiveRecord::Base
    belongs_to :post
  end
  </code></pre>
  
  <p>I'm attempting to find the most recent Post that has at least one Comment.</p>
  
  <p>I tried this:   </p>
  
  <pre><code>@post = Post.find_by_sql("SELECT *, count(comment.id) AS num_of_comments
    FROM post
    INNER JOIN comment ON post.id = comment.post_id
    WHERE num_of_comments &gt;= 1").last
  </code></pre>
  
  <p>but got an error saying num_of_comments was an unknown column.</p>
  
  <p>Then I tried a method on Post, but that didn't work:</p>
  
  <pre><code>def self.has_been_commented
    where("comments.count &lt;= 1")
  end
  </code></pre>
  
  <p>I then started looking into scopes, and saw the .joins method, but wasn't sure how I could then specify another filter.
  Something like:</p>
  
  <pre><code>scope :has_been_commented, joins(:comments)
  </code></pre>
  
  <p>but then I'm not sure how to specify where(:comments.count >= 1)</p>
  
  <p>Sorry if that is confusing...</p>