title: Rails 4 ActiveRecord query for empty association on self referential has_many association
body: <p>Here's the setup:</p>
  
  <pre><code># app/models/booking.rb
  
  class Booking &lt; ActiveRecord::Base
    # Associations
    belongs_to :parent_booking, class_name: "Booking"
    has_many :child_bookings, class_name: "Booking", foreign_key: "parent_booking_id"
  end
  </code></pre>
  
  <p>This is not a required relationship, so not all Bookings have a parent_booking or child_bookings.</p>
  
  <p>Trying to create a query which returns an ActiveRecord::Relation of all Bookings which do NOT have any child_bookings, regardless of whether parent_booking is present or not.</p>
  
  <p>The following example (based on <a href="https://stackoverflow.com/questions/9613717/rails-find-record-with-zero-has-many-records-associated">this SO question</a>) works for scenarios where the relationship is between different models. However, it does not work with the self referential relationship due to the fact that the records are in the same table. Instead, it returns an ActiveRecord::Relation of all Bookings which do not have a parent_booking.</p>
  
  <pre><code>Booking.includes(:child_bookings).where(bookings: { parent_booking_id: nil })
  </code></pre>
  
  <p>The following returns the correct objects, but is extremely inefficient as it has to query the database for every record. Also, it returns it as an array instead of an ActiveRecord::Relation (more concerned with the inefficiency).</p>
  
  <pre><code>Booking.select { |b| b.child_bookings.empty? }
  </code></pre>
  
  <p>I'm quite possibly overlooking a simple solution, but extensive searching hasn't turned up anything yet. Thanks!</p>