问题描述
我有一个模型缩进。在这我使用STI。一个缩进可以是两种类型的买卖。在购买类我使用一个可选的HAS_ONE关联。
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.
我用Rails 3.2的Postgres数据库。
I am using Rails 3.2 and Postgres as database.
更新:
这是如何产生该查询是如下
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?
推荐答案
我第一次感到困惑的术语购买
和出售
。但是,你的更新,我相信帮助我理解这个问题更多。
I first got confused by the terms purchase
and sale
. But your update I believe helped me understand the problem more.
所以,我的理解是什么,未售出的购买减去销售。下面应该给你的清单:
So what I understood is anything unsold is purchases minus sales. Following should give you that list:
scope :unsold, lambda {includes(:sale).select { |p| !p.sale.present? } }
更新:
发生的事情在这里简要说明:
A brief explanation of what's happening here:
的范围并没有真正做数据库中的所有工作。它做了SQL选择所有的采购,包括加入了销售第一的。这使你在你的购买
表中的所有记录。然后,此范围内回落到红宝石阵列
在选择
方法。该方法返回的所有采购 P
没有出售
这是否定的采购与销售完成。
The scope does not really do all the work in the database. It does a SQL select of all the purchases including the joined sale first. This gives you all the records in your purchases
table. Then this scope falls back to Ruby Array
on the select
method. The method returns all the purchases p
without a sale
which is done by negating purchases with sale.
希望这清除了在什么范围做了一些。
Hope this clears up on what the scope is doing a bit.
更新2:
有一个范围,这就是链式!
A scope that's chainable!
scope :unsold, lambda { where('id not in (?)', Sale.pluck(:linked_indent_id)) }
在此范围内的 ID
取值购买不在出售
的的linked_indent_id
被选中。
In this scope the id
s of Purchases that are not in Sale
's linked_indent_id
are selected.
这篇关于适用范围适用于与自身可选HAS_ONE协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!