范围和关联不起作用
Scopes and associations not working
我正在尝试 return 记录关联是否存在:
我尝试了这些示波器:
class Booking < ActiveRecord::Base
has_one :availability
scope :with_availability, -> {where{availability.not_eq nil}}
scope :without_availability, -> {where{availability.eq nil}}
end
改用实例方法
def with_availability
availability.present?
end
def without_availability
availability.blank?
end
我知道有更好的方法,但这也应该有效:
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
我也尝试通过下面的 link 重现解决方案,但我没能做到(但这可能会有帮助):
Rails - has_one relationship : scopes for associated and non-associated objects
试试这个:
class Booking < ActiveRecord::Base
has_one :availability
scope :with_availability, -> { joins{availability} }
scope :without_availability, -> { joins{availability.outer}.where{availability.id.eq nil} }
end
我正在尝试 return 记录关联是否存在:
我尝试了这些示波器:
class Booking < ActiveRecord::Base
has_one :availability
scope :with_availability, -> {where{availability.not_eq nil}}
scope :without_availability, -> {where{availability.eq nil}}
end
改用实例方法
def with_availability
availability.present?
end
def without_availability
availability.blank?
end
我知道有更好的方法,但这也应该有效:
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
我也尝试通过下面的 link 重现解决方案,但我没能做到(但这可能会有帮助):
Rails - has_one relationship : scopes for associated and non-associated objects
试试这个:
class Booking < ActiveRecord::Base
has_one :availability
scope :with_availability, -> { joins{availability} }
scope :without_availability, -> { joins{availability.outer}.where{availability.id.eq nil} }
end