I have a model Indent. On which I am using STI. An indent can be of two types Sale and Purchase. In purchase class I am using an optional has_one association.
class Purchase < Indent
has_one :sale , :class_name => 'Sale', :foreign_key => 'linked_indent_id'
# Make it work.
scope :unsold, lambda {includes(:sale).where('id not in (select distinct linked_indent_id from indents)')}
end
class Sale < Indent
belongs_to :purchase , :class_name => 'Purchase', :foreign_key => 'linked_indent_id'
end
I just need a scope on Purchase class using which i can find all the purchases which are not having a Sale associated to them.
I am using Rails 3.2 and Postgres as database.
Update:
The query which is getting generated is as follows.
SELECT "indents".* FROM "indents" WHERE "indents"."type" IN ('Purchase') AND
(id not in (select distinct linked_indent_id from indents)) ORDER BY indent_date DESC
Following part of the query is working fine.
=# select distinct linked_indent_id from indents;
linked_indent_id
------------------
15013
15019
(3 rows)
And this is also working fine.
SELECT "indents".* FROM "indents" WHERE "indents"."type" IN ('Purchase') AND
(id not in (15013, 15019)) ORDER BY indent_date DESC
What am i missing in coupling these two parts of query?