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

发布于 2024-12-03 16:32:19 字数 581 浏览 2 评论 0原文

我正在尝试进行元搜索或范围,为我提供所有不具有任何 has_many 关联等于 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"

现在我该如何做相反的事情,找到没有发票的订单? (应始终允许订单确认)

Im trying to make a metasearch or alternatively a scope that gives me all objects that doesnt have any of its has_many-association equal to type == "Something".

Example:

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

Searching for orders that have an invoice is easily done by a custom scope:

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

or metasearch:

:invoice_base_type_equals => "Invoice"

Now how do I do the opposite, find orders that have NO invoice? (OrderAcknowledgements should always be allowed)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

森林很绿却致人迷途 2024-12-10 16:32:19

当试图在我的计算机上解决这个问题时,我最终编写了一条涉及子查询的 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

When trying to figure this out on my computer, i ended up writing a sql statement that involves a subquery. I wonder if maybe you can populate the raw SQL into the where method.

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)")

I gave this a try on my site and it seemed to work. Note that I am using MySQL

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文