Regions and associations do not work

I am trying to return records where the association is present or not:

I tried these areas:

class Booking < ActiveRecord::Base
  has_one :availability

  scope :with_availability, -> {where{availability.not_eq nil}}
  scope :without_availability, -> {where{availability.eq nil}}
end
+4
source share
3 answers

Try the following:

class Booking < ActiveRecord::Base
  has_one :availability

  scope :with_availability, -> { joins{availability} }
  scope :without_availability, -> { joins{availability.outer}.where{availability.id.eq nil} }
end
+3
source

Use instance methods instead

def with_availability
  availability.present?
end

def without_availability
  availability.blank?
end
0
source

, , :

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

, ( ):

Rails - has_one :

0

Source: https://habr.com/ru/post/1608888/


All Articles