Rails 3:可选的has_one关联的范围

时间:2011-07-22 13:57:56

标签: ruby-on-rails ruby-on-rails-3 scope arel

我有两种模式:销售和付款

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

但是,我如何创建一个范围,找出的每笔销售都有相关的付款?

3 个答案:

答案 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