Rails 3: has_one optional association scope

I have two models: Sale and payment

class Sale < ActiveRecord::Base has_one :payment end class SaleCancelation < ActiveRecord::Base belongs_to :payment end 

I want to create two scopes, "with payment" and "without payment".

"with_payment" works easily:

 class Sale < ActiveRecord::Base scope :with_payment, joins( :payment ) end 

But how can I create an area that finds every sale that does not have a payment associated with it?

+4
source share
3 answers

What about:

 scope :without_payment, where( 'id not in (select sales_id from payments)' ) 
+4
source

Another way to do this:

 scope :without_profile, lambda { includes(:user_profile).where('user_profiles.id is null') } 
+4
source
 class Sale < ActiveRecord::Base scope :with_payment, joins( :payment ) scope :without_payment, Sale.all - Sale.with_payment end 
0
source

All Articles