Search code examples
ruby-on-railsrubyruby-on-rails-4squeel

Scopes and associations not working


I'm trying to return records where the association is either present or not:

I tried these scopes:

class Booking < ActiveRecord::Base
  has_one :availability

  scope :with_availability, -> {where{availability.not_eq nil}}
  scope :without_availability, -> {where{availability.eq nil}}
end

Solution

  • Try this:

    class Booking < ActiveRecord::Base
      has_one :availability
    
      scope :with_availability, -> { joins{availability} }
      scope :without_availability, -> { joins{availability.outer}.where{availability.id.eq nil} }
    end