Reputation:
class Project
has_many :quotes
scope :available, ->(business_id) { joins(:quotes).where.not(quotes: { business_id: business_id }) }
scope :active, ->(business_id) { joins(:quotes).where(quotes: { business_id: business_id }) }
end
class Quote
belongs_to :project
end
Hi, I'm trying to define an available
scope which returns a relation of Project
records which don't have a Quote
for a given business_id
. I tried using the above scope, but it's returning an empty relation?
A similar active
scope seems to work fine. The only difference here is the .not()
clause.
Any ideas? Do I have to write raw SQL for this?
Upvotes: 1
Views: 160
Reputation: 52396
This ought to do it.
scope :available, ->(business_id) {where.not(Quote.where("quotes.project_id = projects.id and quotes.business_id = ?", business_id).exists)}
Upvotes: 1