2011-09-09 55 views
0

我试图做一个元搜索或者一个范围,它给了我没有任何has_many-association等于类型==“Something”的所有对象。metasearch has_many所有/ none必须匹配

例子:

class Order < ActiveRecord::Base 
    has_many :billing_base 
end 

class InvoiceBase < ActiveRecord::Base 
    belongs_to :order 
end 

class Invoice < InvoiceBase 
end 

class OrderAcknowledgement < InvoiceBase 
end 

搜索有发票很容易通过自定义的范围做订单:

joins(:invoice_base).where(:invoice_base => {:type => "Invoice"}) 

或垂直搜索:

:invoice_base_type_equals => "Invoice" 

现在我该怎么办相反,找到没有发票的订单? (应始终允许OrderAcknowledgements)

回答

0

当试图在我的计算机上解决这个问题时,我最终写了一个涉及子查询的sql语句。我想知道是否可以将原始SQL填充到where方法中。

select * from orders where orders.id not in (SELECT invoice_bases.order_id from invoice_bases); 

where("orders.id not in (SELECT invoice_bases.order_id from invoice_bases)") 

我在我的网站上试了一下,它似乎工作。请注意,我正在使用MySQL

+0

这实际上是我现在这样做的方式(添加“where type ='Invoice'”),但我不确定它是否足够高效,因为考虑到“NOT IN (ID列表)“将成为千位ID的列表。 – vimaz

+0

由于发票库存储了外键值,并且您希望查找所有未连接到发票库的订单,所以您必须全部检查它们。想想它就像比较Ruby中的数组。我同意这不是最漂亮的事情。但是,在数据库级别的索引列上执行此操作将比在软件方面进行比较快得多。特别是当桌子变大时。 – agmcleod

+0

这确实有用,但只要你有几千条记录,NOT IN开始变得非常昂贵。我觉得那里有更好的解决方案。 – DavidMann10k

相关问题