2021年4月3日星期六

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    
https://stackoverflow.com/questions/66937188/getting-activerecord-query-to-work-with-a-left-outer-join April 04, 2021 at 09:07AM

没有评论:

发表评论