Majiy
Majiy

Reputation: 1920

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?

Upvotes: 4

Views: 3720

Answers (2)

yorch
yorch

Reputation: 7318

Another way to do it:

scope :without_profile, lambda { includes(:user_profile).where('user_profiles.id is null') }

Upvotes: 4

Sam Ruby
Sam Ruby

Reputation: 4340

How about:

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

Upvotes: 4

Related Questions