ActiveRecord (Rails): How to do custom (SQL) joins in Rails without an association?

Viewed 11136

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.

1 Answers
Related