我有一个模型缩进。 在这我使用STI。 缩进可以有两种类型的买卖。 在购买类我使用一个可选的HAS_ONE关联。
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
我只需要使用它我可以找到所有这些都没有关联到他们销售的采购采购类范围。
我使用Rails 3.2和Postgres数据库。
更新:
这是越来越生成查询如下。
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
查询下面的部分是工作的罚款。
=# select distinct linked_indent_id from indents;
linked_indent_id
------------------
15013
15019
(3 rows)
这也是工作的罚款。
SELECT "indents".* FROM "indents" WHERE "indents"."type" IN ('Purchase') AND
(id not in (15013, 15019)) ORDER BY indent_date DESC
我失去了在查询中的这两部分耦合是什么?