怎么做Arel中的“where exists”

你如何进行包含Arel中“where exists”的查询? 例如,在这样的查询中,向所有供应商显示至少一个订单:

SELECT * FROM suppliers WHERE EXISTS (SELECT * FROM orders WHERE suppliers.supplier_id = orders.supplier_id); 

我在Arel文档http://rubydoc.info/gems/arel/2.0.7/Arel/Nodes/Exists中看到“存在”,但我在使用它时遇到了麻烦。

干得好:

 suppliers= Supplier.arel_table orders= Order.arel_table suppliers_with_orders = Supplier.where( Order.where(orders[:supplier_id] .eq(suppliers[:id])).exists).to_sql => "SELECT `suppliers`.* FROM `suppliers` WHERE (EXISTS (SELECT `orders`.* FROM `orders` WHERE `suppliers`.`id` = `orders`.`supplier_id`))" 

虽然,内部联接会以更简单的方式执行此操作 – 最终效果不佳 – :

Supplier.joins:订单

我认为你可以整齐地使用counter_cache:

http://asciicasts.com/episodes/23-counter-cache-column