2011-09-09 56 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

相關問題