元搜索has_many所有/无必须匹配

时间:2011-09-09 16:51:17

标签: ruby-on-rails ruby-on-rails-3 has-many sti meta-search

我试图创建一个元搜索或者一个范围,它给了我所有没有任何has_many-association的对象等于type ==“Something”。

示例:

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)

1 个答案:

答案 0 :(得分: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