【发布时间】:2014-01-10 02:31:48
【问题描述】:
我有一个模型缩进。我正在使用 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
我只需要一个 Purchase 类的范围,使用它我可以找到所有没有与之关联的销售的购买。
我使用 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
在耦合查询的这两个部分时我缺少什么?
【问题讨论】:
标签: ruby-on-rails postgresql activerecord ruby-on-rails-3.2