Scopes and associations not working

58 views Asked by At

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
3

There are 3 answers

0
Alexey Shein On BEST ANSWER

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
1
patrickh003 On

Use instance methods instead

def with_availability
  availability.present?
end

def without_availability
  availability.blank?
end
0
Nickolay Kondratenko On

I know there is better way but this should work as well:

class Booking < ActiveRecord::Base
  has_one :availability

  scope :with_availability, -> {where(id: Availability.pluck(:booking_id))}
  scope :without_availability, -> {where.not(id: Availability.pluck(:booking_id))}
end

Also I tried to reproduce the solution by the link below but I didn't manage to do this (but it could be helpful):

Rails - has_one relationship : scopes for associated and non-associated objects