title: Using scope to only show items that have associated objects
body: <p>I am using <a href="https://github.com/ernie/meta_search" rel="nofollow">meta_search</a> to filter through a listing of cars. The car model is defined like this:</p>
  
  <pre><code>class Car &lt; ActiveRecord::Base
    has_many    :images, :class_name =&gt; "CarImage"
    ......
  end
  </code></pre>
  
  <p>I want to define a scope that can be used with meta_search, and to <strong>return only the cars that have at least an image</strong>. The only way I could make it work is to write a join inside the scope, but that seems to return duplicate car objects:</p>
  
  <pre><code>scope :with_images, joins(:images)
  </code></pre>
  
  <p>If I try to select only distinct values, like this:</p>
  
  <pre><code>scope :with_images, joins(:images).select('DISTINCT cars.*')
  </code></pre>
  
  <p>...I mess up the other methods that rely on my search results (such as avg and count aggregators, with group clauses).</p>
  
  <p>While browsing through the <a href="http://guides.rubyonrails.org/active_record_querying.html#scopes" rel="nofollow">Ruby on Rails Guides</a>, I found a curious example, that might solve my problem, but can't get it to work and I don't really understand how it's done:</p>
  
  <pre><code>scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
  </code></pre>
  
  <p>If I use <code>self.arel_table[:images_count]</code> then it says it's a nil object.</p>
  
  <p>Throughout the application, we really have problems with searching and filtering using attributes from the association tables. We solved some problems by simply moving the attribute to the main <code>cars</code> table, but this is kind of stupid, though it performs fast.</p>
  
  <p>After giving it a thought, what would be viable in my opinion is, that the association would first get the list of all cars ids in the current search that have at least one image (this could be done with a simple <code>INNER JOIN</code> and <code>DISTINCT id</code> query) and then use the list of id-s to get the normal listing query, but with a <code>WHERE id IN [id_1, id_2, id_3, ... , id_n]</code> clause.</p>
  
  <p>Would that seem reasonable to you? And how would I do that? :D</p>
  
  <p>Also, would be nice if I could do it without SQL, just with Arel or MetaWhere...</p>