我有两种模式:销售和付款
class Sale < ActiveRecord::Base
has_one :payment
end
class SaleCancelation < ActiveRecord::Base
belongs_to :payment
end
我想创建两个范围,“付款”和“不付款”。
“with_payment”可以轻松实现:
class Sale < ActiveRecord::Base
scope :with_payment, joins( :payment )
end
但是,我如何创建一个范围,找出不的每笔销售都有相关的付款?
答案 0 :(得分:4)
怎么样:
scope :without_payment, where( 'id not in (select sales_id from payments)' )
答案 1 :(得分:4)
另一种方法:
scope :without_profile, lambda { includes(:user_profile).where('user_profiles.id is null') }
答案 2 :(得分:0)
class Sale < ActiveRecord::Base
scope :with_payment, joins( :payment )
scope :without_payment, Sale.all - Sale.with_payment
end