I can write this query which touches 2 tables and gives me the results I want:
select inv.* from
item_to_sku its
left join inventory inv on its.sku_id=inv.sku_id
where its.item_id in (12345, 67890)
And I can come close to it in Rails with this:
ItemToSku.includes(:sku => :inventory).find_all_by_item_id([12345, 67890])
But that pointlessly involves the SKU table in this. Since both ItemToSku and Inventory have a sku_id, I want to just join them directly together like in the SQL version above.
Without adding confusing associations onto my many-to-many table model (ItemToSku), how can I write an appropriate ActiveRecordy way of doing this? I've been playing with .joins() but I can't find any examples of using .joins without existing associations. The main reason I don't want to create the associations is that there are like 20 associations on Sku and more on Item, and it seems silly to duplicate them and thus cloud up the true associations just to optimize one query.
joins
can be used in multiple ways.
i. Join association
Single
Multiple
Nested
ii. Join using raw sql(what you are looking for)
ItemToSku.joins("LEFT JOIN inventory ON item_to_sku.sku_id = inventory.sku_id").where("item_id in (?)", [12345, 67890])
Note: includes
is used for eager loading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With