title: Rails active record scope based on count of has_many scope
body: <p>I have Order model and a Container model with a scope as below:</p>
  
  <pre><code>class Order &lt; ActiveRecord::Base
    has_many :containers, inverse_of: :order, dependent: :destroy
  end
  
  class Container &lt; ActiveRecord::Base
    scope :full_pickup_ready, -&gt; { where.not(full_pickup_ready_date: nil) }
  end
  </code></pre>
  
  <p>The order model has a field call <code>quantity</code> which represents the quantity of containers the order requires but is not necessarily the size of the containers association as not all container data is entered at the time of order creation.</p>
  
  <p>I would like to have a scope on the Order model based on whether the count of the containers with a full_pickup_ready_date is less than the quantity field of the order.</p>
  
  <p>I know I can use merge on the order model to access the scope on the  containers like this:</p>
  
  <pre><code>def self.at_origin
    joins(:containers).merge(Container.full_pickup_ready).uniq
  end
  </code></pre>
  
  <p>but how can I limit the scope to orders where the total number of containers with a full_pickup_ready_date is less that the quantity field on the order?</p>
  
  <p>UPDATE:
  this is reasonably close, but I don't think using the <code>select</code> is efficient:</p>
  
  <pre><code>includes(:containers).select {|o| o.containers.full_pickup_ready.size &lt; o.quantity }
  </code></pre>