范围和协会不起作用

时间:2015-09-24 20:41:29

标签: ruby-on-rails ruby ruby-on-rails-4 squeel

我正在尝试返回关联存在与否的记录:

我试过这些范围:

class Booking < ActiveRecord::Base
  has_one :availability

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

3 个答案:

答案 0 :(得分:3)

试试这个:

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 :(得分:0)

使用实例方法

def with_availability
  availability.present?
end

def without_availability
  availability.blank?
end

答案 2 :(得分:0)

我知道有更好的方法,但这也应该有效:

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 relationship : scopes for associated and non-associated objects