简体   繁体   中英

Getting ActiveRecord Query to work with a left outer join

I'm not sure what I'm doing wrong syntactically here, would appreciate help. An InventoryItem has many MaintenanceOrders . Each MaintenanceOrder has a boolean field that is still_usable . Logically, I want to run a query for all InventoryItems that are still usable, meaning they EITHER don't have any MaintenanceOrders at all, OR that none of their MaintenanceOrders have a flag of still_usable: false .

Quick Rspec

describe "test query" do
 before do
   InventoryItem.create(random_id:"a")
   InventoryItem.create(random_id:"b")
   InventoryItem.create(random_id:"c")

   InventoryItem.where(random_id:"a").last.maintenance_orders.create(still_usable:false)
   InventoryItem.where(random_id:"b").last.maintenance_orders.create(still_usable:nil)
   InventoryItem.where(random_id:"b").last.maintenance_orders.create(still_usable:true)


   @query = InventoryItem.left_outer_joins(:maintenance_orders).where.not(maintenance_orders:{still_rentable:false}).distinct
 end
 it "should return b & c" do
   expect(@query.map(&:random_id)).to match_array(["b","c"])
   # a has a maintenance order with flag still_usable:false so is excluded
   # b has maintenance orders, but none have flag still_usable:false, so is included
   # c has no maintenance orders, so is included
 end
end

You can achieve it using SQL NOT EXISTS

InventoryItem.where("NOT EXISTS (
   SELECT * FROM maintenance_orders 
   WHERE (maintenance_orders.inventory_item_id = inventory_items.id) 
   AND maintenance_orders.still_rentable = false)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM