Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Scope on an optional has_one association

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 easyly:

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

But how can I create a scope that finds every sale that does not have an associated Payment?

like image 736
Majiy Avatar asked Feb 23 '23 12:02

Majiy


2 Answers

How about:

scope :without_payment, where( 'id not in (select sales_id from payments)' )
like image 167
Sam Ruby Avatar answered Mar 05 '23 19:03

Sam Ruby


Another way to do it:

scope :without_profile, lambda { includes(:user_profile).where('user_profiles.id is null') }
like image 40
yorch Avatar answered Mar 05 '23 20:03

yorch