Nathan Hurst Nathan Hurst - 2 years ago 86
Ruby Question

How to do "where exists" in Arel

How do you do a query that includes a "where exists" in Arel? For example on a query like this to show all the suppliers with at least one order:

FROM suppliers
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);

I see "exists" in the Arel docs but I'm having trouble using it.

Answer Source

Here you go:

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

Though, an inner join would do this in a more simple - and eventually less performant - way :

Supplier.joins :orders

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download