4

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
Batman
  • 5,563
  • 18
  • 79
  • 155
  • Which one doesn't work? Second one looks good (note the round braces `()` in first one) – Alexey Shein Sep 24 '15 at 20:48
  • Do you get any error? Could you please show `Booking.without_availability.to_sql`? – Alexey Shein Sep 24 '15 at 20:57
  • `"SELECT \"bookings\".* FROM \"bookings\" WHERE \"bookings\".\"availability\" IS NULL"` – Batman Sep 24 '15 at 21:05
  • 1
    what fields are you doing the comparison with? availability is a table. Am I missing something? – patrickh003 Sep 24 '15 at 21:05
  • Yea availability is a table. ` Booking should have 1 Availability. But sometimes a booking gets created with an Associated availability (bug I haven't tracked down yet). So I'm trying to return all Bookings which might not have an Availability associated with it. – Batman Sep 24 '15 at 21:21

3 Answers3

3

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
Alexey Shein
  • 7,342
  • 1
  • 25
  • 38
0

Use instance methods instead

def with_availability
  availability.present?
end

def without_availability
  availability.blank?
end
patrickh003
  • 168
  • 1
  • 5
0

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

Community
  • 1
  • 1
Nickolay Kondratenko
  • 1,871
  • 2
  • 21
  • 25